I'm trying to figure out how to print an NxN matrix diagonally. Right now I can print the left to right diagonal but not the right to left. So let's say the matrix is:
1 2 3
4 5 6
7 8 9
Now I can print left to right:
1
4 2
7 5 3
8 6
9
But I want also to print right to left:
3
6 2
9 5 1
8 4
7
Here is the code for left to right:
public static void printLeftToRightDiagonal(int[][] matrix) {
int length = matrix.length;
int diagonalLines = (length + length) - 1;
int itemsInDiagonal = 0;
int midPoint = (diagonalLines / 2) + 1;
for (int i = 1; i <= diagonalLines; i++) {
int rowIndex;
int columnIndex;
if (i <= midPoint) {
itemsInDiagonal++;
for (int j = 0; j < itemsInDiagonal; j++) {
rowIndex = (i - j) - 1;
columnIndex = j;
System.out.print(matrix[rowIndex][columnIndex] + " ");
}
} else {
itemsInDiagonal--;
for (int j = 0; j < itemsInDiagonal; j++) {
rowIndex = (length - 1) - j;
columnIndex = (i - length) + j;
System.out.print(matrix[rowIndex][columnIndex] + " ");
}
}
System.out.println();
}
}
I tried to figure out the pattern but I was left without ideas