Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active June 14, 2018 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/4131ecb779b7228a4e4ceadec27d06b8 to your computer and use it in GitHub Desktop.
Save JadenGeller/4131ecb779b7228a4e4ceadec27d06b8 to your computer and use it in GitHub Desktop.
Rotate in place
def transpose_matrix(size, matrix):
for y in range(size):
for x in range(y):
matrix[y][x], matrix[x][y] = matrix[x][y], matrix[y][x]
def flip_y_matrix(size, matrix):
for y in range(size // 2):
flip_y = size - y - 1
for x in range(size):
matrix[x][y], matrix[x][flip_y] = matrix[x][flip_y], matrix[x][y]
def rotate_matrix(size, matrix):
transpose_matrix(size, matrix)
flip_y_matrix(size, matrix)
def print_matrix(size, matrix):
for y in range(size):
for x in range(size):
print(matrix[y][x], end="")
print()
matrix = [list(row) for row in [
"ABCD",
"LMNE",
"KP0F",
"JIHG"
]]
rotate_matrix(4, matrix)
print_matrix(4, matrix)
import itertools
def shift_refs(indices, get, set):
prev_index = indices[-1]
last_value = get(prev_index)
iter = reversed(indices)
next(iter)
for index in iter:
set(prev_index, get(index))
prev_index = index
set(indices[0], last_value)
def rotate_matrix(size, matrix):
for y in range(size // 2):
for x in range(y, size - y - 1):
def indices(x, y):
while True:
yield x, y
y, x = x, size - 1 - y
def get(coord):
x, y = coord
return matrix[y][x]
def set(coord, v):
x, y = coord
matrix[y][x] = v
shift_refs(list(itertools.islice(indices(x, y), 4)), get, set)
def print_matrix(size, matrix):
for y in range(size):
for x in range(size):
print(matrix[y][x], end="")
print()
matrix = [list(row) for row in [
"ABCD",
"LMNE",
"KP0F",
"JIHG"
]]
rotate_matrix(4, matrix)
print_matrix(4, matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment