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

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.

2011/3/3 Jen [email protected]:

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.

Use Marshal:

a= [“qwe”, “asd”]
b = 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.

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

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}’