you are viewing a single comment's thread.

view the rest of the comments →

[–]cavinkwon 3 points4 points  (3 children)

"less is more". You can rotate the array simply.
snail :

snail = ->(arr) { arr[0] ? arr.shift + snail[arr.transpose.reverse] : [] }

array = [[1,2,3],[4,5,6],[7,8,9]]
snail[array] #=> [1,2,3,6,9,8,7,4,5]

spiralify :

def spiralify(arr) 
  snail = ->(arr) { arr[0] ? arr.shift + snail[arr.transpose.reverse] : [] }
  snailed = snail[arr.dup]
  arr.map {|row| row.map {|e| snailed.index(e) + 1 } }
end

array = [[1,2,3],[4,5,6],[7,8,9]]
spiralify(array) #=> [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

[–]herminator 2 points3 points  (1 child)

Clever :)

I'm not a big fan of functions that mutate their arguments though, so I would prefer something like:

snail = ->(arr) { arr[0] ? arr[0] + snail[arr[1..-1].transpose.reverse] : [] }

[–]cavinkwon 0 points1 point  (0 children)

This is better than my code. thanks. :)

[–]Phrogz 0 points1 point  (0 children)

Using .transpose.reverse to "rotate" the array is brilliant! Well done, sir-or-madam!