Skip to content

Commit b1117eb

Browse files
authored
Merge pull request #28 from rroque98/rotateMatrix
Add JavaScript solution to 1.7 Rotate Matrix
2 parents efc4b34 + b15908a commit b1117eb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*Given an image represented by an N*N matrix where
2+
each pixel in the image is 4 bytes, write a method
3+
to rotate the image by 90 degrees. Can you do this
4+
in place?*/
5+
6+
const rotateImage = nestedArr => {
7+
const n = nestedArr.length;
8+
if (n === 0 || n === 1) {
9+
return nestedArr;
10+
}
11+
var rotatedArr = [];
12+
for (let col = 0; col < n; col++) {
13+
let newRow = [];
14+
for (let row = n - 1; row >= 0; row--) {
15+
newRow.push(nestedArr[row][col]);
16+
}
17+
rotatedArr.push(newRow);
18+
}
19+
return rotatedArr;
20+
};
21+
22+
// TESTS:
23+
console.log(
24+
JSON.stringify(rotateImage([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) ===
25+
JSON.stringify([[7, 4, 1], [8, 5, 2], [9, 6, 3]])
26+
);
27+
console.log(JSON.stringify(rotateImage([[1]])) === JSON.stringify([[1]]));
28+
console.log(JSON.stringify(rotateImage([[]])) === JSON.stringify([[]]));
29+
console.log(JSON.stringify(rotateImage([])) === JSON.stringify([]));

0 commit comments

Comments
 (0)