Skip to content

Instantly share code, notes, and snippets.

@cronin101
Created October 31, 2013 12:02
Show Gist options
  • Select an option

  • Save cronin101/7248550 to your computer and use it in GitHub Desktop.

Select an option

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.)
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]
@tef
Copy link
Copy Markdown

tef commented Oct 31, 2013

If I import izip as zip from itertools, the above code doesn't make copies.

If you're not worried about copies, well

def spiral_flatten(matrix):
    out = []
    while matrix:
        out.extend(matrix.pop(0))
        matrix = list(reversed(zip(*matrix)))
    return out

@tef
Copy link
Copy Markdown

tef commented Oct 31, 2013

Aaand in ruby

def spiral_flatten(matrix)
    matrix = Array.new(matrix)
    out = []
    until matrix.empty? do
        out.concat(matrix.shift)
        matrix = matrix.transpose.reverse
    end
    out
end

Edit: Threw in a copy, because

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