Write a function called "spiral" that takes an NxM array as input and returns a "spiral" path through the array, starting in the upper-left corner and moving clockwise. Use the language of your choice.
For example (in Ruby), if
array = [[1,2,3],
[8,9,4],
[7,6,5]]
then
spiral(array) # => [1,2,3,4,5,6,7,8,9]
It should work on any NxM array, so don't assume the input is a square array. However, every row will have the same number of elements.
So there aren't any spoilers, if you decide to solve it please fork this gist and link to the fork in a comment. :)
Hey @O-I, ending up with
nil
in the final result and having to callArray#compact
is usually a code smell. There's typically a way to restructure the code so that they're not generated in the first place.Array#flatten
is often a code smell, too, and where it's not you are almost always reimplementing Enumerable#flat_map. In this case it's the former. You should just be using Array#concat instead of Array#<<.