Reputation: 113
I am trying to iterate a square 2d array for all diagonals from top left to bottom right. I have code to iterate from bottom left to top right but I need to adapt it to also iterate the other way.
public static void main(String[] args) {
int[][] a = {
{1, 2, 3, 4},
{0, 1, 2, 3},
{-1, 0, 1, 2},
{-2, -1, 0, 1},
};
for (int j = 0; j <= a.length + a.length - 2; j++) {
for (int k = 0; k <= j; k++) { // cols
int l = j - k; // rows
if (l < a.length && k < a.length) {
System.out.print(a[l][k] + " ");
}
}
System.out.println();
}
}
The results are:
1
0 2
-1 1 3
-2 0 2 4
-1 1 3
0 2
1
Which is the bottom left to top right diagonals. How can I adapt the method to print diagonals the other way to produce the following results:
-2
-1 -1
0 0 0
1 1 1 1
2 2 2
3 3
4
Thanks for your help.
Upvotes: 3
Views: 2850
Reputation: 587
Just have to mirror the row address
public static void main(String[] args) {
int[][] a = {
{1, 2, 3, 4},
{0, 1, 2, 3},
{-1, 0, 1, 2},
{-2, -1, 0, 1},
};
for (int j = 0; j <= a.length + a.length - 2; j++) {
for (int k = 0; k <= j; k++) { // cols
int l = j - k; // rows
int mirror = a.lenght - l;
if (mirror >= 0 && mirror < a.length && k < a.length) {
System.out.print(a[mirror][k] + " ");
}
}
System.out.println();
}
}
Upvotes: 4