Skip to content

Instantly share code, notes, and snippets.

@Locke23rus
Last active December 17, 2015 23:48
Show Gist options
  • Select an option

  • Save Locke23rus/5691438 to your computer and use it in GitHub Desktop.

Select an option

Save Locke23rus/5691438 to your computer and use it in GitHub Desktop.
require 'text-table'
class SpiralMatrix
DIRECTIONS = [
{ x: 1, y: 0 },
{ x: 0, y: 1 },
{ x: -1, y: 0 },
{ x: 0, y: -1 }
]
def initialize(n)
@n = n.to_i
@a = []
@n.times { @a << Array.new(@n) }
fill
end
def to_s
table = Text::Table.new
@a.each_with_index do |o, i|
table.rows << :separator if i > 0 && i < @n
table.rows << o
end
table.to_s
end
def to_a
@a
end
private
def fill
x = -1
y = 0
i = 1
while i <= @n * @n
DIRECTIONS.each do |v|
dx = x + v[:x]
dy = y + v[:y]
while dx < @n && dy < @n && @a[dy][dx].nil?
x += v[:x]
y += v[:y]
@a[y][x] = i
i += 1
dx = x + v[:x]
dy = y + v[:y]
end
end
end
end
end
puts SpiralMatrix.new(ARGV[0] || gets)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment