static double[] RunGeneticAlgorithm(Task task, int pop_size, int iterations, int tournament_size, double crossover_rate, double mutation_rate) { Population population = new Population(task.n, pop_size); var bestScores = new double[iterations]; for (int i = 0; i < iterations; i++) { population.Evaluate(task); Population new_population = new Population(pop_size); for (int j = 0; j < pop_size; j++) { Individual parent1 = population.Tournament(tournament_size, task); Individual parent2 = population.Tournament(tournament_size, task); Individual child = parent1.Crossover(parent2, crossover_rate); child.Mutate(mutation_rate); new_population.individuals[j] = child; } population = new_population; List <int> scores = new List <int>(); foreach (Individual el in population.individuals) { scores.Add(el.score); } bestScores[i] = (double)scores.Max(); } return(bestScores); }
public void NewGeneration() { if (Population.Count <= 0) { return; } CalculateFitness(); List <Individual <T> > newPopulation = new List <Individual <T> >(); for (int i = 0; i < Population.Count; i++) { Individual <T> firstParent = ChooseParent(); Individual <T> secondParent = ChooseParent(); Individual <T> child = firstParent.Crossover(secondParent); child.Mutate(MutationRate); newPopulation.Add(child); } this.Population = newPopulation; this.Generation++; }
static int RunGeneticForComparison(Task task, int pop_size, int iterations, int tournament_size, double crossover_rate, double mutation_rate) { geneticTime.Start(); Population population = new Population(task.n, pop_size); var bestScores = new double[iterations]; for (int i = 0; i < iterations; i++) { population.Evaluate(task); Population new_population = new Population(pop_size); for (int j = 0; j < pop_size; j++) { Individual parent1 = population.Tournament(tournament_size, task); Individual parent2 = population.Tournament(tournament_size, task); Individual child = parent1.Crossover(parent2, crossover_rate); child.Mutate(mutation_rate); new_population.individuals[j] = child; } population = new_population; } geneticTime.Stop(); ts = geneticTime.Elapsed; return(population.individuals.Max((a) => a.score)); }