Created
April 4, 2016 16:50
-
-
Save zackthehuman/9825cb2638c99a3cf6adb7ec7b04aeb5 to your computer and use it in GitHub Desktop.
JavaScript 2D array rotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr1 = [ | |
['1', '2', '3', '4'], | |
['5', '6', '7', '8'], | |
['9', 'a', 'b', 'c'], | |
['d', 'e', 'f', 'g'], | |
]; | |
function rotCCW(arr) { | |
var n = arr.length; | |
var ret = new Array(n); | |
// Give the return value the right dimensions. | |
for(var i = 0; i < n; i++) { | |
ret[i] = new Array(n); | |
} | |
var x = 0, y = 0; | |
for(x = 0; x < n; x++) { | |
for(y = 0; y < n; y++) { | |
ret[y][x] = arr[x][n - y - 1]; | |
} | |
} | |
return ret; | |
} | |
function rotCW(arr) { | |
var n = arr.length; | |
var ret = new Array(n); | |
// Give the return value the right dimensions. | |
for(var i = 0; i < n; i++) { | |
ret[i] = new Array(n); | |
} | |
var x = 0, y = 0; | |
for(x = 0; x < n; x++) { | |
for(y = 0; y < n; y++) { | |
ret[y][x] = arr[n - x - 1][y]; | |
} | |
} | |
return ret; | |
} | |
console.log(rotCW(arr1)); | |
console.log(rotCCW(arr1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment