genetic-algorithm-js icon indicating copy to clipboard operation
genetic-algorithm-js copied to clipboard

Deep vs. shallow copy

Open PastCoder opened this issue 2 years ago • 1 comments

Hi Miguel, after 7 years your implementation is still a helpful and easy to understand implementation. Thanks for providing it!

Just one thing took me a while of debugging (i.e. because in Javascript I am more a trial-and-error developer): In der function breed() the slide does only a shallow copy of the best half of the population. As I am using more complex structures as individuals, this caused the problem that the individuals did still have some shared references so that I lost my best indivduals when modifying others.

After I did the following change, it worked: Instead of let newPopulation = population.slice(0, breeders); I use now let newPopulation = JSON.parse(JSON.stringify(population.slice(0, breeders)));

Maybe this solution would make your implementation more robust also for complex structures.

Edit: It seems there are a few more places like let parentA = JSON.parse(JSON.stringify(population[parentAIndex].individual)); let parentB = JSON.parse(JSON.stringify(population[parentBIndex].individual));

PastCoder avatar Oct 29 '23 10:10 PastCoder

Nice solution. I'll have to test it a bit and see how it performs in some other test cases.

lodenrogue avatar Mar 08 '24 05:03 lodenrogue