HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Matrix rotation efficiency

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
efficiencymatrixrotation

Problem

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  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

Solution

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.

Context

StackExchange Code Review Q#48097, answer score: 3

Revisions (0)

No revisions yet.