From: "Eric I." Date: 2007-01-15T00:40:09+09:00 Subject: Re: Number Spiral (#109) [solution] Here's my solution to the quiz. I used a recursive solution. An odd-sized spiral is the smaller-by-one even-sized spiral with a number added to the end of each row, and a new row across the bottom. And an even-sized spiral is the smaller-by-one odd-sized spiral with a number added to the beginning of each row and a new row across the top. I decided to make my solution use relatively few lines of code. However in doing that I added some inefficiencies, where a value might be calculated multiple times in a loop/iterator when it would have been better to calculate it once before the loop/iterator, and use that stored value in the loop/iterator. With respect to not building the solution in an array and then displaying the array, I read that to mean not creating a two-dimensional array (i.e., array of arrays) in which to build the entire spiral. I assemble each line of output in an array before displaying that line, but each line is displayed before any subsequent lines are calculated. The solution could be adapted to avoid even the one-dimensional array. Eric ---------------- Interested in on-site, hands-on Ruby training? At www.LearnRuby.com you can read previous students' reviews! ================ def odd_spiral(size, row) if row < size - 1 : even_spiral(size - 1, row) << (size - 1)**2 + row else (0...size).collect { |n| size**2 - 1 - n } end end def even_spiral(size, row) if row == 0 : (0...size).collect { |n| size**2 - size + n } else odd_spiral(size - 1, row - 1).unshift(size**2 - size - row) end end size = (ARGV[0] || 8).to_i (0...size).each do |row| puts ((size % 2 == 0 ? even_spiral(size, row) : odd_spiral(size, row)). map { |n| n.to_s.rjust((size**2 - 1).to_s.length) }.join(" ")) end