Skip to content

Instantly share code, notes, and snippets.

@dliberalesso
Created December 5, 2013 20:41
Show Gist options
  • Save dliberalesso/7813488 to your computer and use it in GitHub Desktop.
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.
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
@dliberalesso
Copy link
Author

[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]] BECOMES [1, 2, 3, 6, 9, 8, 7, 4, 5]

@joelibaceta
Copy link

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