From: Victor Reyes Date: 2007-10-29T06:58:41+09:00 Subject: How do I define a dynamic Matrix or .... ------=_Part_5983_18733542.1193608720108 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hello Team, On my quest to learn Ruby, I implemented a known algorithm to solve an odd nXn magic square. I tested my code using a 3x3 and a 5x5 magic squares. The problem that I am having is that I hard-code the initialization matrix. In other words, if it is a 3x3 I define: mm = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] For a 5 x 5 I define : mm = [[0,0,0, 0, 0], [0,0,0, 0, 0], [0,0,0, 0, 0],[0,0,0,0,0],[0,0,0,0,0]] I want to be able to solve any size odd magic square. To do so, I need to be able to define my matrix dynamically and on demand. Can anyone tell me how to do that? Attached is my current code. Please feel free to criticize it and make recommendations. My disclaimer: I am a Ruby apprentice. Thank you Victor #!/usr/local/bin/ruby -d -W0 def mag(size) r = 0 # row c = 0 # column index = 0 # pointer # mm = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] mm = [[0,0,0, 0, 0], [0,0,0, 0, 0], [0,0,0, 0, 0],[0,0,0,0,0],[0,0,0,0,0]] maxLoop = size * size # Magic Square size 1.upto(maxLoop) do |n| case when n == 1 c = (size / 2).floor # Will keep the integer part, giving us the center in row 0 mm[c][r] = n # This is: mm[c][0] when index >= size index = 0 r = r + 1 mm[c][r] = n puts " " else c = c + 1 if c >= size c = 0 end r = r -1 if r < 0 r = size - 1 end mm[c][r] = n end index = index + 1 puts "[#{c}][#{r}] = #{mm[c][r]} " end # End upto ############## # Output the matrix # ############## puts 0.upto(size -1) do |r| 0.upto(size -1) do |c| print "#{mm[c][r]} " end puts " " end end # End method mag # We start here p1 = ARGV[0].to_i mag( p1 ) ------=_Part_5983_18733542.1193608720108--