Created
December 5, 2013 20:41
-
-
Save dliberalesso/7813488 to your computer and use it in GitHub Desktop.
Sort an array of arrays like a snail (clockwise spiral sorting) with Ruby.
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 snail(array) | |
result = Array.new | |
n = array.length | |
runs = n.downto(0).each_cons(2).to_a.flatten | |
delta = [[1,0], [0,1], [-1,0], [0,-1]].cycle | |
x, y = -1, 0 | |
for run in runs | |
dx,dy = delta.next | |
run.times do |i| | |
x += dx | |
y += dy | |
result << array[y][x] | |
end | |
end | |
result | |
end |
you could use this code too
def snail(array)
array.empty? ? [] : array.shift + snail(array.transpose.reverse)
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]] BECOMES [1, 2, 3, 6, 9, 8, 7, 4, 5]