I am not sure if I should be using recursion or not or if it even helps in increasing the performance of my algorithm. I feel as though I am creating and replacing too many arrays by calling my inner rotate()
function.
Should I add a check to convert rotation -270
to 90
and vice-versa so that I am rotating less often?
Please refer to the JSFiddle I have provided for details and clarification on the functions involved in the code below: JSFiddle Demo
var rotateMatrix = function (matrix, n, direction) {
var ret = matrix.slice();
var rotate = function(direction, matrix) {
var r = zeroArr(n, n);
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
if (direction < 0) {
r[i][j] = matrix[n - j - 1][i];
} else {
r[i][j] = matrix[j][n - i - 1];
}
}
}
return r;
};
for (var turn = Math.abs(direction); turn > 0; turn -= 90) {
ret = rotate(direction, ret);
}
return ret;
};
var tile = [
['A', 'B', 'C'],
['D', 'E', 'F'],
['G', 'H', 'I']
];
trace2('Rotate +180', printMatrix(rotateMatrix(tile, 3, 180)));
trace2('Rotate +90', printMatrix(rotateMatrix(tile, 3, 90)));
trace2('Orginal', printMatrix(tile));
trace2('Rotate -90', printMatrix(rotateMatrix(tile, 3, -90)));
trace2('Rotate -180', printMatrix(rotateMatrix(tile, 3, -180)));
Output:
Rotate +180:
I| H| G
--+--+--
F| E| D
--+--+--
C| B| A
Rotate +90:
C| F| I
--+--+--
B| E| H
--+--+--
A| D| G
Orginal:
A| B| C
--+--+--
D| E| F
--+--+--
G| H| I
Rotate -90:
G| D| A
--+--+--
H| E| B
--+--+--
I| F| C
Rotate -180:
I| H| G
--+--+--
F| E| D
--+--+--
C| B| A