Search code examples
javascriptfor-loopmatrixrotationskip

Javascript for loop skipping a rotation inside matrix


I have been pounding my head for a while now, trying to figure out why my for loops skips a rotation in my matrix. I am trying to make it print out [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8]], that being the whole matrix.

function solve(args)
{
    let arr = args[0].split(' ').map(Number),
        rows = +arr[0],
        cols = +arr[1];

    let matrix = new Array(rows);
    matrix.fill();
    for (let i in matrix)
    {
        matrix[i] = new Array(cols);
    }

    for (let row = 0; row < rows; row++)
    {
        matrix[row][0] = Math.pow(2, row);
        for (let col = matrix[row][0]; col < cols; col++)
        {
            matrix[row][col] = +col + 1;
        }
    }
    console.log(matrix);
}

solve([
  '3 5'  
]);

P.S. I tried this too:

for (let row = 0; row < rows; row++)
    {
        matrix[row][0] = Math.pow(2, row);
        for (let col = matrix[row][0]; col < cols; col++)
        {
            matrix[row][col] = +col + matrix[row][0];
        }
    }

Solution

  • I hope this helps you. While starting with a certain value as first element (matrix[row][0]) you can increment each row by 1 iteratively:

    function solve(args)
    {
      let arr = args[0].split(' '),
      rows = +arr[0],
      cols = +arr[1];
      let matrix = new Array(rows);
      matrix.fill();
      for (let i in matrix)
      {
        matrix[i] = new Array(cols);
      }
      for (let row = 0; row < matrix.length; row++) {
        matrix[row][0] = Math.pow(2, row);
        for (let col = 1; col < matrix[row].length; col++) {
          matrix[row][col] = col + matrix[row][0];
        }
      }
      console.log(matrix);
      return matrix;
    }
    
    solve([
    '3 5'
    ]);