RosettaCodeData/Task/Spiral-matrix/Ruby/spiral-matrix-1.rb

19 lines
501 B
Ruby
Raw Permalink Normal View History

2013-04-11 01:07:29 -07:00
def spiral(n)
spiral = Array.new(n) {Array.new(n, nil)} # n x n array of nils
runs = n.downto(0).each_cons(2).to_a.flatten # n==5; [5,4,4,3,3,2,2,1,1,0]
2013-06-05 21:47:54 +00:00
delta = [[1,0], [0,1], [-1,0], [0,-1]].cycle
2013-04-11 01:07:29 -07:00
x, y, value = -1, 0, -1
for run in runs
2014-01-17 05:32:22 +00:00
dx, dy = delta.next
run.times { spiral[y+=dy][x+=dx] = (value+=1) }
2013-04-11 01:07:29 -07:00
end
spiral
end
2013-06-05 21:47:54 +00:00
def print_matrix(m)
2015-02-20 00:35:01 -05:00
width = m.flatten.map{|x| x.to_s.size}.max
m.each {|row| puts row.map {|x| "%#{width}s " % x}.join}
2013-06-05 21:47:54 +00:00
end
2013-04-11 01:07:29 -07:00
print_matrix spiral(5)