Skip to content
Advertisement

Storing lower triangle of a matrix into an array

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]

Advertisement

Answer

  1. The number of elements in the resulting array is n * (n + 1) / 2 as it is a sum of arithmetic progression from 1 to n
  2. When creating the result array, the indexes change like this:
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 4×4, 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]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement