------ art_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
@square ill
end
def fill
square rray.new(@n)
square.each_index { |row| square[row] rray.new(@n) }
current
row
col @n/2+1)-1
square[row][col] urrent
until current @n**2
current+ row ove_down(row)
col ove_down(col)
unless square[row][col].nil?
2.times { |i| row ove_up(row) }
col ove_up(col)
end
square[row][col] urrent
end
square
end
def move_down(val)
if (val-1) > -1
val -
else
val @n-1)
end
val
end
def move_up(val)
if (val+1) > (@n-1)
val
else
val +
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 agicSquare.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 |
+--------------------------------------------+
------ art_53455_27534308.1179671822002--