public void NewGeneration() { if (!Population.Any()) { return; } CalculateFitness(); var newPopulation = new List <Dna <T> >(); for (int i = 0; i < Population.Count; i++) { Dna <T> parent1 = ChooseParent(); Dna <T> parent2 = ChooseParent(); Dna <T> child = parent1.Crossover(parent2); child.Mutate(MutationRate); newPopulation.Add(child); } Population = newPopulation; Generation++; }
public Dna <T> Crossover(Dna <T> otherParent) { var child = new Dna <T>(Genes.Length, _getRandomGene, _fitnessFunction, false); for (int i = 0; i < Genes.Length; i++) { child.Genes[i] = rnd.NextDouble() < 0.5 ? Genes[i] : otherParent.Genes[i]; } return(child); }
private void CalculateFitness() { _fitnessSum = 0; Dna <T> best = Population[0]; Population.ForEach(p => { _fitnessSum += p.CalculateFitness(Population.IndexOf(p)); best = best.Fitness < p.Fitness ? p : best; }); BestFitness = best.Fitness; best.Genes.CopyTo(BestGenes, 0); }