Skip to content

Instantly share code, notes, and snippets.

@themactep
Created November 22, 2012 09:28
Show Gist options
  • Save themactep/4130195 to your computer and use it in GitHub Desktop.
Save themactep/4130195 to your computer and use it in GitHub Desktop.
Outward spiral matrix builder
#!/usr/bin/env ruby
#
# Outward spiral matrix builder
# 2012, Paul Philippov <themactep@gmail.com>
#
def show_usage
puts 'Usage: $0 <number>'
exit
end
def print_matrix(matrix)
matrix.each do |row|
puts row.join(' ')
end
end
def spiral_matrix(n)
movement = [[1,0],[0,1],[-1,0],[0,-1]]
direction = nil
max_length = n.to_s.length
output_format = "%-#{max_length}d"
max_x = max_y = Math.sqrt(n).floor
if max_x * max_y < n
max_x += 1
max_y += 1 if max_x * max_y < n
end
matrix = Array.new(max_x) { Array.new(max_y) { ' ' * max_length } }
x, y, side, side_steps, steps_to_go = -1, 0, 1, max_x, 0
n.downto(1) do |i|
if steps_to_go == 0
movement.push(direction = movement.shift)
side += 1
if side > 2
side = 1
side_steps -= 1
end
steps_to_go = side_steps
end
x += direction[0]
y += direction[1]
matrix[y][x] = output_format % i
steps_to_go -= 1
end
print_matrix matrix
end
if ARGV.empty?
show_usage
end
n = ARGV[0].to_i
if n == 0
puts 'Error: Argument is not a number!'
show_usage
end
spiral_matrix(n)
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment