Back to Freecodecamp

Challenge 27: Matrix Rotate

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295a.md

latest1.3 KB
Original Source

--description--

Given a matrix (an array of arrays), rotate the matrix 90 degrees clockwise and return it. For instance, given [[1, 2], [3, 4]], which looks like this:

12
34

You should return [[3, 1], [4, 2]], which looks like this:

31
42

--hints--

rotate([[1]]) should return [[1]].

js
assert.deepEqual(rotate([[1]]), [[1]]);

rotate([[1, 2], [3, 4]]) should return [[3, 1], [4, 2]].

js
assert.deepEqual(rotate([[1, 2], [3, 4]]), [[3, 1], [4, 2]]);

rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) should return [[7, 4, 1], [8, 5, 2], [9, 6, 3]].

js
assert.deepEqual(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[7, 4, 1], [8, 5, 2], [9, 6, 3]]);

rotate([[0, 1, 0], [1, 0, 1], [0, 0, 0]]) should return [[0, 1, 0], [0, 0, 1], [0, 1, 0]].

js
assert.deepEqual(rotate([[0, 1, 0], [1, 0, 1], [0, 0, 0]]), [[0, 1, 0], [0, 0, 1], [0, 1, 0]]);

--seed--

--seed-contents--

js
function rotate(matrix) {

  return matrix;
}

--solutions--

js
function rotate(matrix) {
  const n = matrix.length;
  const result = Array.from({ length: n }, () => Array(n).fill(0));

  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      result[j][n - 1 - i] = matrix[i][j];
    }
  }

  return result;
}