[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: How do I define a dynamic Matrix or ....

Todd Benson

10/28/2007 11:05:00 PM

On 10/28/07, 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]]
>
> 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 )

irb> odd_matrix_number = 7
irb> my_matrix - Array.new(odd_matrix_number) {
Array.new(odd_matrix_number) {0} }

I'm not sure exactly what is your assignment, but it might be good to
create a MagicSquare object.

My half a cent.

Todd

1 Answer

Todd Benson

10/28/2007 11:11:00 PM

0

On 10/28/07, Todd Benson <caduceass@gmail.com> wrote:

> irb> odd_matrix_number = 7
> irb> my_matrix - Array.new(odd_matrix_number) {
> Array.new(odd_matrix_number) {0} }
>
> I'm not sure exactly what is your assignment, but it might be good to
> create a MagicSquare object.
>
> My half a cent.
>
> Todd

That is supposed to be...

irb> my_matrix = Array.new(odd_matrix_number) {
Array.new(odd_matrix_number) {0} }

("=" in place of the original "-")

Somebody get me away from this particular keyboard :-)

Todd