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
The problem can be divided into two tasks:
The first rule is equivalent to write a method like below:
//example for matrix[2, 2] it will print 9 5 1
private static void printReverseDiagonal(int[][] matrix, int i, int j) {
System.out.print(matrix[i][j]);
for (int row = i - 1, column = j - 1; row >= 0 && column >= 0; --row, --column) {
System.out.print(" " + matrix[row][column]);
}
System.out.println();
}
The second rule is equivalent to write one cycle iterating over elements matrix[0, n - 1], matrix[1, n - 1] ... matrix[n - 1, n - 1] and another one iterating over elements matrix[n - 2, n - 1], matrix[n - 3, n - 1] .... matrix[0, n - 1] like below:
public static void printRightToLeftDiagonal(int[][] matrix) {
int n = matrix.length;
int j = n - 1;
for (int i = 0; i < n; ++i) {
printReverseDiagonal(matrix, i, j);
}
int i = n - 1;
for(j = n - 2; j >= 0; --j) {
printReverseDiagonal(matrix, i, j);
}
}
Combining the two functions you obtain your expected result.
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