On 5/20/07, Harry Kakueki <list.push / gmail.com> wrote:
> 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:
> >
>

# Slight improvement to my first solution.
# I moved the 1 into the range (1..num**2) and deleted the old line
that input the 1.
# I didn't see a reason to keep it out of the range. So I saved a step.
# Also, I initialized the arrays with the value "empty".

### 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,"empty"))}

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

    if tot[0][mid] != "empty"
    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] == "empty"
  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/