Hi --

On 28/10/2007, Victor Reyes <victor.reyes / gmail.com> wrote:
> 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]]

You can just do something like this:

mm = []
size.to_i.times { mm << Array.new(size.to_i,0) }

Incidentally, have you looked into the numerous Matrix/math libs