On 5/18/07, Ruby Quiz <james / grayproductions.net> wrote:
>
> This week's Ruby Quiz is to write a program that builds magic squares.  To keep
> the problem easy, I will say that your program only needs to work for odd values
> of N.  Try to keep your runtimes pretty reasonable even for the bigger values of
> N:
>
# Here is my solution.
# It is based on the steps at Wikipedia.
# http://en.wikipedia.org/wiki/Magic_square#A_method_for_constructing_a_magic_square_of_odd_order
# I input the 1 in the middle of the first array (tot[0][mid]).
# Then I moved the arrays into position so I could always input using
the same index (tot[0][mid]).

### Code Start
num = ARGV[0].to_i
if num % 2 != 0 and num > 0
mid = ((num + 1) / 2) - 1
tot = []
num.times {tot.push(Array.new(num))}
tot[0][mid] = 1.to_s.rjust((num**2).to_s.length)

  (2..num**2).each do |x|
  tot.unshift(tot.pop)
  tot.each {|g| g.push(g.shift)}

    if tot[0][mid] != nil # Square is already filled ?
    2.times {tot.push(tot.shift)}
    tot.each {|g| g.unshift(g.pop)}
    tot[0][mid] = x.to_s.rjust((num**2).to_s.length)
    end

    tot[0][mid] = x.to_s.rjust((num**2).to_s.length) if tot[0][mid] == nil
  end

tot.push(tot.shift)
tot.each {|x| p x.join(" ")}
end
###

# Harry

-- 

A Look into Japanese Ruby List in English
http://www.kakueki.com/