How to zigzag numbers in floyd's triangle pattern?
Solution 1:
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i
of i
numbers has a lowest value (i² - i + 2)/2
,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
- step -1
- step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
Solution 2:
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Solution 3:
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415