Here is my solution. I used a recursive printing routine to handle the
insides of the middle rows.
Ben
class NumberSpiral
def initialize(n)
@size = n
@format = "%#{(n*n - 1).to_s.length+1}d"
if n % 2 == 0
@top_row = proc{|x| (x*(x-1)).upto(x*x-1) {|i| print_num(i) } }
@bottom_row = proc{|x| ((x-1)*(x-1)).downto((x-1)*(x-2)) {|i|
print_num(i) } }
@middle_first = proc{|x,row| print_num(x*(x-1)-row) }
@middle_last = proc{|x,row| print_num((x-2)*(x-2)-1+row) }
else
@top_row = proc{|x| ((x-1)*(x-2)).upto((x-1)*(x-1)) {|i|
print_num(i) } }
@bottom_row = proc{|x| (x*x-1).downto(x*(x-1)) {|i| print_num(i)
} }
@middle_first = proc{|x,row| print_num((x-1)*(x-2)-row) }
@middle_last = proc{|x,row| print_num((x-1)*(x-1)+row) }
end
end
def print_num(i)
printf @format, i
end
def print_row(size, row)
if row == 0
@top_row.call(size)
elsif row == size - 1
@bottom_row.call(size)
else
@middle_first.call(size, row)
print_row(size-2, row-1)
@middle_last.call(size, row)
end
end
def print_clockwise
@size.times {|i| print_row(@size, i) ; puts ; puts if i < @size-1 }
end
end
if ARGV.size == 0 or not ARGV[0] =~ /^\d+$/
puts "Usage: #$0 N"
puts "Output: Prints a \"spiral\" of numbers that fill a NxN
square."
else
NumberSpiral.new(ARGV[0].to_i).print_clockwise
end
On Jan 12, 9:29 am, Ruby Quiz <j... / grayproductions.net> wrote:
> The three rules of Ruby Quiz:
>
> 1. Please do not post any solutions or spoiler discussion for this quiz until
> 48 hours have passed from the time on this message.
>
> 2. Support Ruby Quiz by submitting ideas as often as you can:
>
> http://www.rubyquiz.com/
>
> 3. Enjoy!
>
> Suggestion: A [QUIZ] in the subject of emails about the problem helps everyone
> on Ruby Talk follow the discussion. Please reply to the original quiz message,
> if you can.
>
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
>
> by Bob Showalter
>
> (Taken from the puzzle by William Wu athttp://www.ocf.berkeley.edu/~wwu/riddles/cs.shtml)
>
> [Editor's Note: This was also a code golf problem a few months back:http://codegolf.com/oblongular-number-spirals --JEG2]
>
> Write a Ruby program to print out a "spiral" of numbers that fill a NxN square.
> Your program will take a single argument to specify the dimensions of the square
> (1 or higher). The number zero represents the center of the spiral, and the
> succeeding integers spiral out in a clockwise (or counterclockwise; your choice)
> direction from the center until the square is filled.
>
> Your program should write the output line by line, without using an array to
> build up the data first.
>
> Here's the output for an 8x8 spiral:
>
> 56 57 58 59 60 61 62 63
>
> 55 30 31 32 33 34 35 36
>
> 54 29 12 13 14 15 16 37
>
> 53 28 11 2 3 4 17 38
>
> 52 27 10 1 0 5 18 39
>
> 51 26 9 8 7 6 19 40
>
> 50 25 24 23 22 21 20 41
>
> 49 48 47 46 45 44 43 42