From: Bryan Weatherly Date: 2007-05-20T23:37:08+09:00 Subject: Re: [QUIZ] Magic Squares (#124) ------=_Part_53455_27534308.1179671822002 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Here is my solution. I also used the steps from Wikipedia: # magic_squares.rb # Ruby Quiz (#124) class MagicSquare def initialize(n) raise ArgumentError, "N must be an odd number." if n%2 == 0 @n = n @square = fill end def fill square = Array.new(@n) square.each_index { |row| square[row] = Array.new(@n) } current = 1 row = 0 col = (@n/2+1)-1 square[row][col] = current until current == @n**2 current+=1 row = move_down(row) col = move_down(col) unless square[row][col].nil? 2.times { |i| row = move_up(row) } col = move_up(col) end square[row][col] = current end square end def move_down(val) if (val-1) > -1 val -= 1 else val = (@n-1) end val end def move_up(val) if (val+1) > (@n-1) val = 0 else val += 1 end val end def display header = "+" + "-" * (@n*5-1) + "+" puts header @square.each do |row| current = "| " row.each do |col| current << " " * ((@n**2).to_s.length - col.to_s.length) current << col.to_s + " | " end puts current puts header end end end if __FILE__ == $0 square = MagicSquare.new(ARGV[0].to_i) square.display end ---------------------- ~/desktop $ ruby magic_squares.rb 9 +--------------------------------------------+ | 45 | 34 | 23 | 12 | 1 | 80 | 69 | 58 | 47 | +--------------------------------------------+ | 46 | 44 | 33 | 22 | 11 | 9 | 79 | 68 | 57 | +--------------------------------------------+ | 56 | 54 | 43 | 32 | 21 | 10 | 8 | 78 | 67 | +--------------------------------------------+ | 66 | 55 | 53 | 42 | 31 | 20 | 18 | 7 | 77 | +--------------------------------------------+ | 76 | 65 | 63 | 52 | 41 | 30 | 19 | 17 | 6 | +--------------------------------------------+ | 5 | 75 | 64 | 62 | 51 | 40 | 29 | 27 | 16 | +--------------------------------------------+ | 15 | 4 | 74 | 72 | 61 | 50 | 39 | 28 | 26 | +--------------------------------------------+ | 25 | 14 | 3 | 73 | 71 | 60 | 49 | 38 | 36 | +--------------------------------------------+ | 35 | 24 | 13 | 2 | 81 | 70 | 59 | 48 | 37 | +--------------------------------------------+ ------=_Part_53455_27534308.1179671822002--