I wrote the following code to walk half the diagonals of an array:
String[][] b = [a,b,c]
[d,e,f]
[g,h,i];
public void LoopD
This is the same as what leoflower posted here. I've just changed the variable names for better understanding.
level = denotes the current level of the diagonal that is being printed. Ex:- level = 2 denotes diagonal elements with indices (0,2),(1,1),(2,0)
currDiagRowIndex = denotes row index of the current diagonal being printed
currDiagColIndex = denotes columnn index of the current diagonal being printed
void printMatrixDiagonal(int matrix[][], int endRowIndex, int endColIndex){
for(int level = 0; level < endColIndex; level++){
for(int currDiagRowIndex = 0, currDiagColIndex = level; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0 ; currDiagRowIndex++, currDiagColIndex--){
System.out.print(matrix[currDiagRowIndex][currDiagColIndex] + " ");
}
System.out.println();
}
for(int level = 1; level < endRowIndex; level++){
for(int currDiagRowIndex = level, currDiagColIndex = endColIndex-1; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0; currDiagRowIndex++, currDiagColIndex--){
System.out.print(matrix[currDiagRowIndex][currDiagColIndex]+ " ");
}
System.out.println();
}
}
Input:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Output:
1
2 6
3 7 11
4 8 12 16
5 9 13 17 21
10 14 18 22
15 19 23
20 24
25