I have code that generates 1 to 10 numbers:
for (int i = 0; i <=10; i++)
{
for (int j = 1; j <=10; j++)
{
int respones = i;
int respones1 = j;
if (respones1 > respones)
{
text.append(String.valueOf(respones1));
}
}
}
I get this result:
12345678910
2345678910
345678910
45678910
5678910
678910
78910
8910
910
10
But, I want this result:
12345678910
23456789101
34567891012
45678910123
56789101234
67891012345
78910123456
89101234567
91012345678
10123456789
How can I get my code so that it moves the first number to the end of the string?
Try this one:
for (int i = 0; i < 10; i++) {
for (int j = i + 1; j <= i + 10; j++) {
int respones = i;
int respones1 = j;
if (respones1 > respones) {
text.append(String.valueOf(respones1 > 10 ? respones1 % 10 : respones1));
}
}
}
I believe the best way to approach this would be to use a deque/queue as it makes rotating the numbers in the sequence achieveable in just two operations.
ArrayDeque<int> deque = new ArrayDeque<int>(10); // Create a queue
for(int i = 1; i <= 10; ++i) // Fill queue with [1..10]
{
deque.addLast(i);
}
StringBuilder builder = new StringBuilder(); // A StringBuilder will be more efficient than string concatenation
for(int i = 1; i <= 10; ++i)
{
for(int item : deque) // Append the queue contents to the string
{
builder.append(item);
}
builder.append("\n"); // New line
int temp = deque.removeFirst(); // Take the first item from the deque
deque.addLast(temp); // And append it to the end of the deque
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With