public void NewGeneration(int numNewDNA = 0, bool crossoverNewDNA = false) { int finalCount = Population.Count + numNewDNA; if (finalCount <= 0) { return; } if (Population.Count > 0) { CalculateFitness(); Population.Sort(CompareDNA); } newPopulation.Clear(); for (int i = 0; i < Population.Count; i++) { if (i < Elitism && i < Population.Count) { newPopulation.Add(Population[i]); } else if (i < Population.Count || crossoverNewDNA) { DNA <T> parent1 = ChooseParent(); DNA <T> parent2 = ChooseParent(); DNA <T> child = parent1.Crossover(parent2); child.Mutate(MutationRate); newPopulation.Add(child); } else { newPopulation.Add(new DNA <T>(dnaSize, random, getRandomGene, fitnessFunction, shouldInitGenes: true)); } } List <DNA <T> > tmpList = Population; Population = newPopulation; newPopulation = tmpList; Generation++; }
public void NewGeneration() { if (Population.Count <= 0) { return; } CalculateFitness(); Population.Sort(CompareDNA); newPopulation.Clear(); for (int i = 0; i < Population.Count; i++) { // we keep the 5 best individual (the list is sorted) if (i < Elitism) { newPopulation.Add(Population[i]); } else { DNA <T> parent1 = ChooseParent(); DNA <T> parent2 = ChooseParent(); DNA <T> child = parent1.Crossover(parent2); child.Mutate(MutationRate); newPopulation.Add(child); } } //Memory optimization (we dont have to always create a new list) List <DNA <T> > tmpList = Population; Population = newPopulation; newPopulation = tmpList; Generation++; }