Search code examples
javascriptarraysalgorithmmatrix2d

Initialize a two-dimensional array with the values shown in the table below


Initialize a two-dimensional array with the values shown in the table below

1   0   0   0   1   0   0   0   1   0
0   4   0   0   0   4   0   0   0   4
0   0   9   0   0   0   9   0   0   0
0   0   0   16  0   0   0   16  0   0
1   0   0   0   25  0   0   0   25  0
0   4   0   0   0   36  0   0   0   36
0   0   9   0   0   0   49  0   0   0
0   0   0   16  0   0   0   64  0   0
1   0   0   0   25  0   0   0   81  0
0   4   0   0   0   36  0   0   0  100

I tried doing a diagonal pattern but can't seem to execute this pattern. This is my diagonal code.

In the above diagram, the diagonal pattern seems to start after every 3 intervals replaced with zeros

function matrixPattern() {
  let arr = [];
  let len = 10;

  for (let i = 0; i < len; i++) {
    arr[i] = [];

    for (let j = 0; j < len; j++) {
      arr[i][j] = i !== j ? 0 : (i + 1) * (j + 1)
    }
  }
  for (let i in arr) {
    let line = '';

    for (let j in arr[i]) {
      line += arr[i][j] + '\t';
    }

    console.log(line);
  }
}
matrixPattern()


Solution

  • You can use modulo logic to identify which diagonals get the non-zero values. Note that the distance between two diagonals is not 3 but 4: the first diagonal starts at (0, 0), and the one at its right at (4, 0)!

    The non-zero values are squares of the minimum distance to the left or the top. So they are not the multiplication of two different values, but two the same values. The inner assignment could be:

    arr[i][j] = (i - j) % 4 ? 0 : (Math.min(i, j) + 1) ** 2
    

    So:

    function matrixPattern() {
      let arr = [];
      let len = 10;
    
      for (let i = 0; i < len; i++) {
        arr[i] = [];
    
        for (let j = 0; j < len; j++) {
          arr[i][j] = (i - j) % 4 ? 0 : (Math.min(i, j) + 1) ** 2;
        }
      }
      return arr; 
    }
    
    const mat = matrixPattern();
    
    for (const row of mat) console.log(...row);