Nested matrix and nested loop problem not working

Viewed 29

This should be the input and output: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]] The returned output is actually the same as the input. What am I doing wrong?

var rotate = function(matrix) {
        let result = matrix;
        let i = 0;
        let index = matrix.length - 1;
        for (let x of matrix) {
            for (let n of x) {
                result[i][index] == n;
                if (i<matrix.length-2)
                i++;    
            }
            index--;
        }
        console.log(result);
        return result;
        };
        
        var list= [[1,2,3],[4,5,6],[7,8,9]];
        
        rotate(list);

1 Answers

const matrix = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];

const rotate = (m) => {
  const n = m.length;
  const r = [ ...m.map(a => []) ];
  
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      r[i][j] = m[n - j - 1][i];
    }
  }
  return r;
}

const result = rotate(matrix);
console.log(result);

Related