Given the problem from "Cracking the coding interview"
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees clockwise.
For simplicity I assumed a matrix of strings for my example so
[["a", "a", "a", "a"],
["b", "b", "b", "b"],
["c", "c", "c", "c"],
["d", "d", "d", "d"]]
becomes
[["d", "c", "b", "a"],
["d", "c", "b", "a"],
["d", "c", "b", "a"],
["d", "c", "b", "a"]]
Here's my JavaScript solution
var rotate = function(matrix) {
// Copy the original matrix
var origMatrix = matrix.slice();
for(var i=0; i < matrix.length; i++) {
// Map each row entry to its rotated value
var row = matrix[i].map(function(x, j) {
var k = (matrix.length - 1) - j;
return origMatrix[k][i];
});
matrix[i] = row;
}
return matrix;
};