@@ -3,22 +3,27 @@ each pixel in the image is 4 bytes, write a method
3
3
to rotate the image by 90 degrees. Can you do this
4
4
in place?*/
5
5
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 ;
9
10
}
10
11
var rotatedArr = [ ] ;
11
- var numOfRows = nestedArr [ 0 ] . length ;
12
- for ( let x = 0 ; x < numOfRows ; x ++ ) {
12
+ for ( let col = 0 ; col < n ; col ++ ) {
13
13
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 ] ) ;
16
16
}
17
17
rotatedArr . push ( newRow ) ;
18
18
}
19
19
return rotatedArr ;
20
- }
20
+ } ;
21
21
22
22
// 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 ( [ [ ] ] ) ) ;
24
29
console . log ( JSON . stringify ( rotateImage ( [ ] ) ) === JSON . stringify ( [ ] ) ) ;
0 commit comments