From: James Koppel <darmaniiii@yahoo.com>
Date: May 18, 2007 1:35:48 PM CDT
To: submission@rubyquiz.com, submission@rubyquiz.com
Subject: Please Forward: Ruby Quiz SubmissionHere is my solution to Ruby Quiz 124. It does not implement the extra credit. It uses the following algorithm (courtesy of Wikipedia):
"Starting from the central column of the first row with the number 1, the fundamental movement for filling the squares is diagonally up and right, one step at a time. If a filled square is encountered, one moves vertically down one square instead, then continuing as before. When a move would leave the square, it is wrapped around to the last row or first column, respectively."
def magic_square(n)
square = .fill(nil,0...n).map{
.fill(nil,0...n)}
x,y = (n-1)/2, 0
nxt = 1
while nxt <= n**2
square[y] = nxt
nxt += 1
if square[(y-n-1)%n][(x+n+1)%n]
y += 1
else
x,y, = (x+n+1)%n,(y-n-1)%n
end
end
square
endn = ARGV[0].to_i
digits = (n**2).to_s.length
square = magic_square(n)
square.map! {|arr| arr.map{|x|" " * (digits - x.to_s.length) + "#{x}"}}
n.times {|t|
puts "+" + ("-" * (n*(digits + 3)-1)) + "+"
puts "| #{square[t].join(' | ')} |"}
puts "+" + ("-" * (n*(digits + 3)-1)) + "+"Pinpoint customers who are looking for what you sell.
ยทยทยท
Begin forwarded message: