Skip to content

Instantly share code, notes, and snippets.

@ravern
Created August 10, 2018 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravern/2be1cd5c01a4b3b7550676318d2ddc6c to your computer and use it in GitHub Desktop.
Save ravern/2be1cd5c01a4b3b7550676318d2ddc6c to your computer and use it in GitHub Desktop.
Matrix Rotation Challenge
# Given an image represented by an NxN matrix, where each pixel in the image is
# 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in
# place?
# Displays the given matrix.
def display(matrix):
N = len(matrix)
for column in range(0, N):
for row in range(0, N):
print(f'{matrix[column][row]:02d} ', end='')
print()
# Rotates the given NxN matrix by 90 degrees.
def rotate(matrix):
# First, create N.
N = len(matrix)
# Second, calculate the number of rings needed.
#
# If N is odd, then the center element does not
# need to rotate. Otherwise, it needs to rotate.
# That is why a floor division is used.
num_rings = N // 2
# Next, loop through each ring and rotate them.
for ring in range(0, num_rings):
# First, calculate the maximum offset of a
# ring.
max_offset = N - (ring * 2) - 1
# Next, loop through each offset and rotate
# the 4 elements.
for offset in range(0, max_offset):
# First, the top left element should be
# stored.
origin = matrix[ring][ring+offset]
# Next, move the bottom left element to
# the top left.
matrix[ring][ring+offset] = matrix[ring+max_offset-offset][ring]
# Next, move the bottom right element to
# the bottom left.
matrix[ring+max_offset-offset][ring] = matrix[ring+max_offset][ring+max_offset-offset]
# Next, move the top right element to
# the bottom right.
matrix[ring+max_offset][ring+max_offset-offset] = matrix[ring+offset][ring+max_offset]
# Finally, set the top right element to
# the origin.
matrix[ring+offset][ring+max_offset] = origin
# Finally, return the matrix
return matrix
matrices = [
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
[
[1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12],
[13, 14, 15, 16]
],
[
[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],
]
]
for matrix in matrices:
print('000 DEGREES')
display(matrix)
print('090 DEGREES')
display(rotate(matrix))
print('180 DEGREES')
display(rotate(matrix))
print('270 DEGREES')
display(rotate(matrix))
print('-----------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment