Skip to content

Instantly share code, notes, and snippets.

@habina
Last active August 29, 2015 14:02
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 habina/489a964e110b4e0e254b to your computer and use it in GitHub Desktop.
Save habina/489a964e110b4e0e254b to your computer and use it in GitHub Desktop.
1.6 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?
def getIndex(x, y, width):
"""
Return the index in 1D array
"""
index = x + y * width
return index
def printMatrix(matrix, width):
"""
Print Matrix row by row
"""
for i in range(width*width):
print(matrix[i], end="\t")
if((i + 1) % width == 0):
print()
def rotateImage(matrix, width):
"""
1.6 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?
"""
"One time transpose + one time horizontally flip = one time rotate clockwise"
"In place transpose"
for y in range(width):
for x in range(y):
temp = matrix[getIndex(x, y, width)]
matrix[getIndex(x, y, width)] = matrix[getIndex(y, x, width)]
matrix[getIndex(y, x, width)] = temp
"In place horizontally flip"
for y in range(0, width*width, width):
for x in range(width//2):
temp = matrix[x + y]
matrix[x + y] = matrix[width - x - 1 + y]
matrix[width - x - 1 + y] = temp
return matrix
width = 4
"Create a N*N matrix"
matrix = list(range(width*width))
print("Before rotated:")
printMatrix(matrix, width)
newMatrix = rotateImage(matrix, width)
print("After rotated:")
printMatrix(newMatrix, width)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment