run method

Map<String, dynamic> run({
  1. int generations = 100,
  2. int tournamentK = 3,
})

Run GA for generations. Returns a map with best and fitness.

Implementation

Map<String, dynamic> run({int generations = 100, int tournamentK = 3}) {
  var population = initPopulation();
  if (population.length != populationSize) {
    // allow flexibility but copy/trim/pad to match size
    final buf = <T>[];
    while (buf.length < populationSize) {
      buf.addAll(population);
    }
    population = buf.sublist(0, populationSize);
  }

  T best = population[0];
  double bestF = fitness(best);

  for (var g = 0; g < generations; g++) {
    // evaluate and sort by fitness descending
    population.sort((a, b) => fitness(b).compareTo(fitness(a)));
    if (fitness(population.first) > bestF) {
      best = population.first;
      bestF = fitness(best);
    }

    final next = <T>[];
    // elitism
    for (var e = 0; e < elitism; e++) {
      next.add(population[e]);
    }

    while (next.length < populationSize) {
      final parentA = _tournament(population, tournamentK);
      final parentB = _tournament(population, tournamentK);
      var child = crossover(parentA, parentB, _rand);
      if (_rand.nextDouble() < mutationRate) child = mutate(child, _rand);
      next.add(child);
    }
    population = next;
  }

  // final evaluation
  population.sort((a, b) => fitness(b).compareTo(fitness(a)));
  best = population.first;
  bestF = fitness(best);
  return {'best': best, 'fitness': bestF};
}