How to make copies of array that do not impact on the original?

J

Jen

Hi,

I'm trying to make a sudoku solver that uses genetic algorithms in Ruby.

My algorithm needs to make multiple copies of the sudoku board
(depending on the population size specified) then populate the empty
spaces in each board with random numbers (not impacting on any other
board).

As the number of board copies I need depends on the population size I
was trying to use a for loop.

Sudo code:
i = 0
for i <= pop (size of pop specified by user)
make copy of board in to board i
end
I want to end up with my copies named board1, board2 etc, depending on
the value of 'i' when the array is created from the original.
If I could do this in a simpler way with blocks please let me know.

Thanks in advance for any suggestions.
 
I

Iñaki Baz Castillo

2011/3/3 Jen said:
I want to end up with my copies named board1, board2 etc, depending on th= e
value of 'i' when the array is created from the original.
If I could do this in a simpler way with blocks please let me know.

Use Marshal:

a=3D ["qwe", "asd"]
b =3D Marshal.load(Marshal.dump a)

b is exactly same as a, but all the objects have been cloned so they
don't point to the same object id.

--=20
I=C3=B1aki Baz Castillo
<[email protected]>
 
P

Paul Mckibbin

Jen wrote in post #985279:
Hi,

I'm trying to make a sudoku solver that uses genetic algorithms in Ruby.
make copy of board in to board i
end
I want to end up with my copies named board1, board2 etc, depending on
the value of 'i' when the array is created from the original.
If I could do this in a simpler way with blocks please let me know.

Thanks in advance for any suggestions.

Wouldn't it be better to have arrays of boards rather than copies with
names like board1, board2 etc.
I'd do something like

original_board=[1,2,3,4,5,6]
board=[]
n.times {board << original_board.dup}

If the array contents are more comples (e.g. references to objects),
then dup won't be good enough, but if it is primitives you are storing,
that will make a copy.

Paul
 
S

Shadowfirebird

My algorithm needs to make multiple copies of the sudoku board
(depending on the population size specified) then populate the empty
spaces in each board with random numbers (not impacting on any other
board).

Not sure if this is helpful or not, but if it were me I'd make a Board class. One of the methods would be the code to populate itself with random numbers. You can then store all instances in an array.

This makes the code pretty simple. To fill all boards with random numbers, just 'boards.each{|b| b.populate}'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,573
Members
45,046
Latest member
Gavizuho

Latest Threads

Top