// New Individual with Identity inherited from 2 parent Individuals. public Individual(Individual parent1, Individual parent2, string target, Random random) { if (parent1.Length != parent2.Length) throw new Exception("Undefined for sequences of unequal length: Crossover"); this.random = random; char[] child = new char[parent1.Length]; // combine the parents randomly for (int i = 0; i < child.Length; i++) { if (random.Next(0, 1) == 0) child[i] = (parent1.IdentityValue.ToCharArray())[i]; else child[i] = (parent2.IdentityValue.ToCharArray())[i]; } if (random.NextDouble() < mutationRate) child = Mutation(child); this.identityValue = new string(child); this.fitness = CalculateFitnessValue(target); }
private void AddToPopulation(Individual newIndividual) { population.Add(newIndividual); census.Add(newIndividual.IdentityValue); }
private Individual Crossover() { Individual newChild = null; // Loop until we have a child that has never existed before. do { Individual Father = population[random.Next(0, population.Count)]; Individual Mother = null; // No asexual reproduction do { Mother = population[random.Next(0, population.Count)]; } while (Mother == Father); newChild = new Individual(Father, Mother, this.FitnessTarget, random); } while (census.Contains(newChild.IdentityValue)); return newChild; }