Skip to content

Commit b15908a

Browse files
committed
Refactor 1.7 Rotate Matrix due to error in initial test logic
1 parent b0c5d06 commit b15908a

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

JavaScript/chapter01/1.7 - Rotate Matrix/rroque98_sol.js

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,27 @@ each pixel in the image is 4 bytes, write a method
33
to rotate the image by 90 degrees. Can you do this
44
in place?*/
55

6-
const rotateImage = (nestedArr) => {
7-
if (nestedArr.length === 0) {
8-
return [];
6+
const rotateImage = nestedArr => {
7+
const n = nestedArr.length;
8+
if (n === 0 || n === 1) {
9+
return nestedArr;
910
}
1011
var rotatedArr = [];
11-
var numOfRows = nestedArr[0].length;
12-
for (let x = 0; x < numOfRows; x++) {
12+
for (let col = 0; col < n; col++) {
1313
let newRow = [];
14-
for (let i = nestedArr.length - 1; i >= 0; i--) {
15-
newRow.push(nestedArr[i][x]);
14+
for (let row = n - 1; row >= 0; row--) {
15+
newRow.push(nestedArr[row][col]);
1616
}
1717
rotatedArr.push(newRow);
1818
}
1919
return rotatedArr;
20-
}
20+
};
2121

2222
// TESTS:
23-
console.log(JSON.stringify(rotateImage([[1,2,3],[4,5,6]])) === JSON.stringify([[4,1],[5,2],[6,3]]));
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([[]]));
2429
console.log(JSON.stringify(rotateImage([])) === JSON.stringify([]));

0 commit comments

Comments
 (0)