Reputation: 97
I want to store the lower triangle of a matrix into a single dimension array.
int matrixSample [][] = {{6,4,1},{7,5,9},{3,2,8}};
6 4 1
7 5 9
3 2 8
When I print the lower triangle it is fine as it has the respected output.
for(int i = 0; i < matrixSample.length; i++){
for(int j = 0; j < matrixSample[0].length; j++){
if(i>=j) {
System.out.print(matrixSample[i][j] + " ");
}
}
System.out.println("");
}
6
7 5
3 2 8
The trouble I am having is with the index position when I try to add the diagonals to a separate array. The right values are collected but in the wrong order. My if()
is allowing matrix[1][0]
to be stored before matrix[1][1]
.
static int[] getAllDiagonalsInMatrix(int matrix[][]){
int diagonal[] = new int[matrix.length * (matrix.length - 1)];
int index = 0;
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[row].length; col++) {
if(row >= col) {
diagonal[index] = matrix[row][col];
index++;
}
}
}
return diagonal;
}
[6, 7, 5, 3, 2, 8]
The result I am looking for is
[6,5,8,7,2,3]
Upvotes: 0
Views: 176
Reputation: 19555
n * (n + 1) / 2
as it is a sum of arithmetic progression from 1 to n
0,0; 1,1; 2,2... n,n
1,0; 2,1; n,n-1
...
n,0
So the inner loop should be rewritten as shown below:
static int[] getLowerDiagonals(int[][] matrix) {
int n = matrix.length;
int m = n * (n + 1) / 2;
int[] res = new int[m];
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
res[k++] = matrix[j + i][j];
}
}
return res;
}
Test:
int matrixSample [][] = {{6,4,1},{7,5,9},{3,2,8}};
for (int[] r : matrixSample) {
System.out.println(Arrays.toString(r));
}
System.out.println("Diagonals: " + Arrays.toString(getLowerDiagonals(matrixSample)));
Output:
[6, 4, 1]
[7, 5, 9]
[3, 2, 8]
Diagonals: [6, 5, 8, 7, 2, 3]
For matrix 4x4, the output is as follows:
int matrixSample [][] = {{6,4,1,2},{7,5,9,3},{3,2,8,6},{3,1,2,4}};
Output:
[6, 4, 1, 2]
[7, 5, 9, 3]
[3, 2, 8, 6]
[3, 1, 2, 4]
Diagonals: [6, 5, 8, 4, 7, 2, 2, 3, 1, 3]
Upvotes: 1
Reputation:
Try this.
static int[] getAllDiagonalsInMatrix(int matrix[][]){
int length = matrix.length;
int diagonal[] = new int[length * (length - 1)];
for (int n = 0, index = 0; n < length; ++n)
for (int row = n, col = 0; row < length; ++row, ++col)
diagonal[index++] = matrix[row][col];
return diagonal;
}
and
int matrixSample [][] = {{6,4,1},{7,5,9},{3,2,8}};
System.out.println(Arrays.toString(getAllDiagonalsInMatrix(matrixSample)));
result:
[6, 5, 8, 7, 2, 3]
Upvotes: 0