Skip to content

Instantly share code, notes, and snippets.

@O-I

O-I/spiral.md Secret

Forked from jfarmer/spiral.md
Last active December 24, 2015 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save O-I/56d3049d9d99de965383 to your computer and use it in GitHub Desktop.
Save O-I/56d3049d9d99de965383 to your computer and use it in GitHub Desktop.

Spiral Path

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.

Your Solution

So there aren't any spoilers, if you decide to solve it please fork this gist and link to the fork in a comment. :)

def spiral(matrix)
matrix.empty? ? [] : matrix.shift + spiral(matrix.transpose.reverse)
end
@jfarmer
Copy link

jfarmer commented Oct 2, 2013

Hey @O-I, ending up with nil in the final result and having to call Array#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#<<.

@O-I
Copy link
Author

O-I commented Oct 2, 2013

Thanks for the helpful comments, @jfarmer. I've refactored my solution taking into account what you've said. Any other suggestions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment