Last active
June 14, 2018 08:50
-
-
Save JadenGeller/4131ecb779b7228a4e4ceadec27d06b8 to your computer and use it in GitHub Desktop.
Rotate in place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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