Skip to content

Instantly share code, notes, and snippets.

@vbrazo
Last active August 24, 2019 18:34
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 vbrazo/bc1d4ad0fcc1c3298d867b034cf5af2c to your computer and use it in GitHub Desktop.
Save vbrazo/bc1d4ad0fcc1c3298d867b034cf5af2c to your computer and use it in GitHub Desktop.
How to rotate a matrix 90 degrees in Ruby
#
# Transpose a matrix
# Make [[1,2,3], [4,5,6], [7,8,9]] becomes [[1,4,7], [2,5,8], [3,6,9]]
#
class Array
def my_transpose
size.times do |i|
0.upto(i) do |j|
self[i][j], self[j][i] = self[j][i], self[i][j]
end
end
self
end
end
#
# Reverse array
# Make [1,4,7] becomes [7,4,1]
#
def my_reverse(array)
reverse = []
i = -1
array.each do
reverse << array[i]
i -= 1
end
reverse
end
#
# Rotate matrix 90
#
def rotate90(array)
array = array.my_transpose
array.map { |row| my_reverse(row) }
end
rotate90([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
rotate90([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
#
# IRB console:
#
2.5.1 :1736 > rotate90([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
=> [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
2.5.1 :1737 > rotate90([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
=> [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment