Skip to content

Instantly share code, notes, and snippets.

@cwg83
Created November 20, 2021 22:41
Show Gist options
  • Save cwg83/9e4af20ffb404f50f66c2505ee996839 to your computer and use it in GitHub Desktop.
Save cwg83/9e4af20ffb404f50f66c2505ee996839 to your computer and use it in GitHub Desktop.
import itertools
given_matrix = [[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36]]
rotations = 2
# Rotate a matrix counterclockwise r times
def matrixRotation(matrix, r):
# Number of rows in the matrix
rows = len(matrix)
# Number of columns in the matrix
columns = len(matrix[0])
# New list that will contain each slice of the matrix in a new list
matrices = []
# The number of slices in the matrix
matrix_num = int(min(rows, columns) / 2)
i = 0
while i < matrix_num:
single_matrix = []
# The top (left to right) of the matrix slice
top = matrix[i][i:columns-i]
# The right side (top to bottom) of the matrix slice
right = [matrix[row][columns-1-i] for row in range(i+1, rows-i-1)]
# The bottom (right to left) of the matrix slice
bottom = matrix[rows-i-1][i:columns-i]
bottom.reverse()
# The left side (bottom to top) of the matrix slice
left = [matrix[row][i] for row in range(i+1, rows-i-1)]
left.reverse()
i += 1
# Append each side of the matrix slice to the single_matrix list, with each side in its own list
single_matrix.extend([top, right, bottom, left])
# Turn the single_matrix list of lists into a single list
single_matrix = [x for x in single_matrix if x != []]
# Turn into a flat list
single_matrix = list(itertools.chain(*single_matrix))
# Rotate this flat list counter clockwise by r
# If r is more than the length of the matrix it's more efficient to use r % len
new_r = r % len(single_matrix)
for _ in range(new_r):
single_matrix.append(single_matrix.pop(0))
# Append the rotated list to the matrices list
matrices.append(single_matrix)
flat_matrices = list(itertools.chain(*matrices))
new_matrix = [[] for i in range(rows)]
i = 0
rs = rows
cs = columns
# Create new matrix from rotated matrix
while i <= matrix_num:
# Create new top
new_matrix[i][i:i] = flat_matrices[:cs]
del flat_matrices[:cs]
# Create new right side
for k in range(rs - 2):
new_matrix[k + 1 + i].insert(i, flat_matrices[k])
del flat_matrices[:rs - 2]
# Create new bottom
new_matrix[rows - 1 - i][i:i] = flat_matrices[:cs][::-1]
del flat_matrices[:cs]
# Create new left side
for k in range(rs - 2):
new_matrix[rs - 2 - k + i].insert(i, flat_matrices[k])
del flat_matrices[:rs - 2]
i += 1
rs -= 2
cs -= 2
# Print each row as a string joined by a space
for row in new_matrix:
print(' '.join(str(x) for x in row))
matrixRotation(given_matrix, rotations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment