Skip to content

Instantly share code, notes, and snippets.

@ShayDavidson
Created December 13, 2012 16:34
Show Gist options
  • Save ShayDavidson/4277721 to your computer and use it in GitHub Desktop.
Save ShayDavidson/4277721 to your computer and use it in GitHub Desktop.
Print a spiral matrix.
def print_spiral(mat)
layers = (mat.length.to_f / 2).ceil
layers.times do |layer|
print_layer(mat, layer, layers)
end
end
def print_layer(mat, layer, layers)
if mat.length.odd? and (layer == layers - 1)
puts mat[layer][layer]
else
print_top(mat, layer)
print_right(mat, layer)
print_bottom(mat, layer)
print_left(mat, layer)
end
end
def print_top(mat, layer)
row = layer
layer.upto(mat.length-layer-2) do |col|
puts mat[row][col]
end
end
def print_right(mat, layer)
col = mat.length-1-layer
layer.upto(mat.length-layer-2) do |row|
puts mat[row][col]
end
end
def print_bottom(mat, layer)
row = mat.length-1-layer
(mat.length-1-layer).downto(layer+1) do |col|
puts mat[row][col]
end
end
def print_left(mat, layer)
col = layer
(mat.length-1-layer).downto(layer+1) do |row|
puts mat[row][col]
end
end
def init_matrix(size)
(1..size**2).each_slice(size).to_a
end
print_spiral(init_matrix(4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment