Skip to content

Instantly share code, notes, and snippets.

@manzhikov
Forked from dliberalesso/snail.rb
Created August 19, 2017 21:42
Show Gist options
  • Save manzhikov/593e7625fd5edd82fbea2e930dbb049e to your computer and use it in GitHub Desktop.
Save manzhikov/593e7625fd5edd82fbea2e930dbb049e 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment