breedNewGeneration method

Generation<P, G, R> breedNewGeneration(
  1. List<Generation<P, G, R>> precursors
)

Implementation

Generation<P, G, R> breedNewGeneration(List<Generation<P, G, R>> precursors) {
  var newGen = Generation<P, G, R>();
  var pool = precursors.last.members.toList(growable: false);
  assert(pool.every((P ph) => ph.result != null));
  pool.sort((P a, P b) => (a.result!.compareTo(b.result!)));
  var length = precursors.last.members.length;

  // Elitism
  for (var i = 0; i < elitismCount; i++) {
    var clone1 = createBlankPhenotype();
    clone1.genes = pool[i].genes;
    newGen.members.add(clone1);
  }

  // Crossover breeding
  while (newGen.members.length < length) {
    var parent1 = getRandomTournamentWinner(pool);
    var parent2 = getRandomTournamentWinner(pool);
    var child1 = createBlankPhenotype();
    var child2 = createBlankPhenotype();
    var childrenGenes = crossoverParents(parent1, parent2,
        crossoverPointsCount: parent1.genes.length ~/ 2);
    child1.genes = childrenGenes[0];
    child2.genes = childrenGenes[1];
    newGen.members.add(child1);
    newGen.members.add(child2);
  }
  // Remove the phenotypes over length.
  while (newGen.members.length > length) {
    newGen.members.removeLast();
  }
  newGen.members
      .skip(elitismCount) // Do not mutate elite.
      .forEach((P ph) => mutate(ph));
  return newGen;
}