Created
October 31, 2013 12:02
-
-
Save cronin101/7248550 to your computer and use it in GitHub Desktop.
Flattening a matrix stored as a list of lists, in clockwise spiral pattern.
From a coding interview - sorry about the Ruby, recruiters (I'm not actually sorry.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def spiral_flatten(matrix_chunks) | |
| [].tap do |result| | |
| until matrix_chunks.empty? | |
| result.concat matrix_chunks.shift | |
| matrix_chunks[0..-2].to_a.each { |chunk| result << chunk.pop } | |
| break if matrix_chunks.empty? | |
| result.concat matrix_chunks.pop.reverse | |
| matrix_chunks[1..-1].to_a.reverse_each { |chunk| result << chunk.shift } | |
| end | |
| end | |
| end | |
| spiral_flatten [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] | |
| #=> [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Aaand in ruby
Edit: Threw in a copy, because