4
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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 Apr 25 '14 at 10:37
  • \$\begingroup\$ @Mr.Polywhirl Concerning changes to reviewed code, you might want to read this meta-post \$\endgroup\$ – Vogel612 Apr 25 '14 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.