A matrix will be in M x N format.So what we need to do is, get value of indexes from 0,0 to M,N.
Itreate the two dimensional array in diagonally as follow
After diagonal traverse the output will be.
Consider the above output
TraveseMatrixDiagonally.java
Reference Link https://www.youtube.com/watch?v=T8ErAYobcbc
50 36 22
31 88 87
27 73 95
50
31 36
27 88 22
73 87
95
50
31 36
27 88 22
- These elements start from left to right top
- Need to iterate for 0 to M-1 using for loop and display corresponding elements diagonally using a while loop.
- To find next element use for formula: M-1,N+1 in while loop
73 87
95
- These elements start from bottom to right top
- Need to Iterate form 1 to N-1 in for loop and display corresponding elements diagonally using a while loop.
- So to find next element use for formula, M-1,N+1 in while loop
TraveseMatrixDiagonally.java
public class TraveseMatrixDiagonally {
private static final int M = 4;
private static final int N = 4;
public static void main(String[] args) {
TraveseMatrixDiagonally app = new TraveseMatrixDiagonally();
int[][] matrix = app.createMatrix();
app.printMatrix(matrix);
app.traverseDiagonally(matrix);
}
private void traverseDiagonally(int[][] matrix) {
for (int i = 0; i <= M - 1; i++) {
int X = i; // temp M
int Y = 0; // temp N
while (X >= 0 && Y <= N - 1) {
System.out.print(matrix[X][Y] + " ");
X = X - 1;
Y = Y + 1;
}
System.out.println(" ");
}
for (int i = 1; i <= N - 1; i++) {
int X = M - 1;
int Y = i;
while (X >= 0 && Y <= N - 1) {
System.out.print(matrix[X][Y] + " ");
X = X - 1;
Y = Y + 1;
}
System.out.println(" ");
}
}
private int[][] createMatrix() {
int matrix[][] = new int[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = (int) ((Math.random() * (99 + 1 - 10)) + 10);
}
}
return matrix;
}
private void printMatrix(int[][] matrix) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j]);
System.out.print(" ");
}
System.out.println(" ");
}
}
}
/*
****** SAMPLE INPUT ********
61 44 88
74 44 32
86 56 92
******* INPUT ********
****** SAMPLE OUTPUT ********
61
74 44
86 44 88
56 32
92
******* OUTPUT ********
*/
No comments:
Post a Comment