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.

JavaScript

When I print the lower triangle it is fine as it has the respected output.

JavaScript

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].

JavaScript

The result I am looking for is

JavaScript

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:
JavaScript

So the inner loop should be rewritten as shown below:

JavaScript

Test:

JavaScript

Output:

JavaScript

For matrix 4×4, the output is as follows:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement