Search code examples
javascriptloopsmatrixnested-loops

Creating and Populating a Matrix via Loop?


I am currently trying to approach a basic programming exercise that requires you to form a matrix via a for loop and nested loop.

The matrix should be:

0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0

I can't quite figure out the logic needed to approach this despite knowing the basics of for loops. I am struggling to visualize how a loop would create this as I am thinking of it creating 5 arrays such as [1,0,1,2,3] etc.

How can one use nested loops to achieve this?


Solution

  • Imagine a matrix as a list of lists - in this case, a list of rows.

    let width = 5;
    let height = 5;
    let matrix = [];
    for (let i=0; i<height; i++) {
      let row = []
      for (let j=0; j<width; j++) {
        row.push(Math.abs(i - j));
      }
      matrix.push(row);
    }
    console.log(matrix.join('\n'));