Skip to content

Instantly share code, notes, and snippets.

@O-I O-I/spiral.md Secret forked from jfarmer/spiral.md
Last active Dec 24, 2015

Embed
What would you like to do?

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

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.