• + 0 comments

    speed boost! avoid unnecessary rotations

    def matrixRotation(matrix, r):
        # Write your code here
        hDim = len(matrix[0])
        vDim = len(matrix)
        nbLayers = min(vDim / 2, hDim / 2)
        
        
        for layerNb in range(int(nbLayers)):
            
            innerVDim = vDim-layerNb*2
            innerHDim = hDim-layerNb*2
              
            # massive speed increase! why moving everything to end at the same point?
            fullRotationMoves = innerVDim*2+innerHDim*2-4
            rotationsToDo = r % fullRotationMoves
            
            for rr in range(rotationsToDo):
                bottomLeftHold = matrix[-1 - layerNb][layerNb] + 0  # bottom left
                topRightHold = matrix[layerNb][-1 - layerNb] + 0  # top right
    
    
                # move down on the left
                for iD in reversed(range(layerNb, layerNb+innerVDim)):
                    if iD > 0:
                        matrix[iD][layerNb] = matrix[iD - 1][layerNb] + 0
    
    
                # move up on the right
                for iU in range(layerNb, layerNb+innerVDim-1):
                    if iU < layerNb+innerVDim:
                        matrix[iU][hDim - 1 - layerNb] = matrix[iU + 1][hDim - 1 - layerNb] + 0
    
    
                # move bottom to right
                if innerHDim > 2:  # only if the horizontal dimension is > 2
                    for iR in reversed(range(layerNb+1, layerNb+innerHDim)):
                        matrix[-1 - layerNb][iR] = matrix[-1 - layerNb][iR - 1] + 0
    
    
                # move top to left
                if innerHDim > 2:  # only if the horizontal dimension is > 2
                    for iL in range(layerNb, layerNb+innerHDim-1):
                        matrix[layerNb][iL] = matrix[layerNb][iL+1] + 0
    
    
                # apply bottomLeftHold
                matrix[-1-layerNb][layerNb+1] = bottomLeftHold+0
                # apply topRightHold
                matrix[layerNb][layerNb+innerHDim-2] = topRightHold+0
    
            
    
        for i in range(m):
            print(' '.join(map(str, matrix[i])))
        return matrix