MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / rotate

Function rotate

matrix/rotate-image.js:7–40  ·  view source on GitHub ↗
(matrix)

Source from the content-addressed store, hash-verified

5 * @return {void} Do not return anything, modify matrix in-place instead.
6 */
7var rotate = function (matrix) {
8 if (!matrix || matrix.length === 0 || matrix.length !== matrix[0].length) {
9 throw new Error("invalid matrix");
10 }
11 if (matrix.length < 2) {
12 return matrix; // no need to do anything to rotate a 1,1 matrix
13 }
14
15 let len = matrix.length - 1,
16 half = Math.floor(matrix.length / 2);
17 // loop through diagonal
18 for (let layer = 0; layer < half; layer++) {
19 let first = layer;
20 let last = len - layer;
21 for (let i = first; i < last; i++) {
22 let offset = i - first;
23 let top = matrix[first][i]; //save top
24
25 // bottom left => top left
26 matrix[first][i] = matrix[last - offset][first];
27
28 // bottom right => bottom left
29 matrix[last - offset][first] = matrix[last][last - offset];
30
31 // top right => bottom right
32 matrix[last][last - offset] = matrix[i][last];
33
34 // top left => top right
35 matrix[i][last] = top;
36 }
37 }
38
39 return matrix;
40};
41// var rotate = function(matrix) {
42// if (!matrix || matrix.length === 0 || matrix.length !== matrix[0].length) {
43// throw new Error('invalid matrix');

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected