Created
February 26, 2013 20:53
-
-
Save andrewberls/5042077 to your computer and use it in GitHub Desktop.
Function to rotate matrices
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
function rotateMatrix(matrix, numRot) { | |
var result = [], | |
buf = []; | |
if (numRot != 0) { | |
for (var i=0; i<matrix.length; i++) { | |
for (var j=0; j<matrix.length; j++) { | |
buf.push(matrix[j][i]) | |
} | |
result.push(buf.reverse()) | |
buf = [] | |
} | |
return rotateMatrix(result, numRot-1); | |
} else { | |
return matrix; | |
} | |
} | |
// TEST CASES | |
// ------------------------------------ | |
// Utility function to inspect a matrix | |
function printMatrix(matrix) { | |
var line = ""; | |
for (var i = 0; i < matrix.length; i++) { | |
for (var j = 0; j < matrix[i].length; j++) { | |
if (typeof matrix[i][j] !== 'undefined') { | |
line += matrix[i][j]; | |
line += " "; | |
} | |
} | |
console.log(line); | |
line = ""; | |
} | |
} | |
var matrix = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
[10,11,12], | |
] | |
matrix = rotateMatrix(matrix, 2) | |
printMatrix(matrix) | |
// expected 1: | |
// | |
// [10,7,4,1] | |
// [11,8,5,2] | |
// [12,9,6,3] | |
// expected 2: | |
// | |
// 12 11 10 | |
// 9 8 7 | |
// 6 5 4 | |
// 3 2 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment