Search code examples
pythonalgorithmarray-algorithms

Array in-place rotater returning wrong values


I wish to define a function to rotate a matrix by 90 degrees in place

def rotate_matrix(matrix):
        for i in range(len(matrix)//2):
            for j in range(i, len(matrix)-i-1):
                matrix[~j][i], matrix[i][j], matrix[j][~i], matrix[~i][~j] = matrix[i][j], matrix[j][~i], matrix[~i][~j], matrix[~j][i]
        return matrix

When inserting :

[
 [a, b],
 [c, d]
]

it returns:

[
 [b, d],
 [a, c]
]

instead of:

[
 [c, a],
 [d, b]
]

and I'm unsure why.


Solution

  • You were on the right track! Your code performs a counterclockwise rotation instead of clockwise.
    To solve it you have to make a few small changes to the assignment logic:

    def rotate_matrix(matrix):
            for i in range(len(matrix)//2):
                for j in range(i, len(matrix)-i-1):
                    matrix[~j][i], matrix[i][j], matrix[j][~i], matrix[~i][~j] = \
                    matrix[~i][~j], matrix[~j][i], matrix[i][j], matrix[j][~i]
            return matrix
    

    does what you are looking for.


    However, I would use numpy, as it has a built in method for rotating matrices:

    import numpy as np
    mat = np.array([['a','b'],
             ['c','d']])
    
    def rotate_matrix(matrix):
        return np.rot90(matrix, 3) // * SEE NOTE
    
    print(rotate_matrix(mat))
    

    Returns:

    [['c' 'a']
     ['d' 'b']]
    


    NOTE: the rot90 method offers counterclockwise rotation. Since you request clockwise rotation, you must specify an argument of 3 to specify the amount of counterclockwise rotations that should be made to achieve a clockwise rotation.