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
1 Answer 1
The n
parameter is redundant, as it should be possible to deduce the matrix dimensions from matrix
itself, using matrix.length
and matrix[0].length
. You seem to have made the assumption that matrix
is square — you should either document or relax the restriction.
I suggest writing three separate inner functions for the three possible rotations. One code-reuse technique you could use for the ±90° rotations is to combine transpose and row-swap operations.
-
\$\begingroup\$ Wow, that question was insightful. I have come up with the ollowing: Updated JSFiddle. Should I append these changes to my question for others to view? Is there any other way to optimize this? \$\endgroup\$Mr. Polywhirl– Mr. Polywhirl2014年04月25日 10:37:30 +00:00Commented Apr 25, 2014 at 10:37
-
\$\begingroup\$ @Mr.Polywhirl Concerning changes to reviewed code, you might want to read this meta-post \$\endgroup\$Vogel612– Vogel6122014年04月25日 16:51:21 +00:00Commented Apr 25, 2014 at 16:51