// Evolves a population over one generation public static Population evolvePopulation(Population pop) { Population newPopulation = new Population(pop.populationSize(), false); // Keep our best individual if elitism is enabled int elitismOffset = 0; if (elitism) { newPopulation.saveTour(0, pop.getFittest()); elitismOffset = 1; } // Crossover population // Loop over the new population's size and create individuals from // Current population for (int i = elitismOffset; i < newPopulation.populationSize()-1; i++) { // Select parents Tour parent1 = tournamentSelection(pop); Tour parent2 = tournamentSelection(pop); // Crossover parents //if (rdm1.NextDouble() < 0.8) //{ Tour[] child = crossover(parent1, parent2); // Add child to new population newPopulation.saveTour(i++, child[0]); newPopulation.saveTour(i, child[1]); //} //else //newPopulation.saveTour(i, parent1); } Tour parent3 = tournamentSelection(pop); Tour parent4 = tournamentSelection(pop); // Crossover parents //if (rdm1.NextDouble() < 0.8) //{ Tour[] child1 = crossover(parent3, parent4); // Add child to new population newPopulation.saveTour(newPopulation.populationSize() - 1, child1[0]); // Mutate the new population a bit to add some new genetic material for (int i = elitismOffset; i < newPopulation.populationSize(); i++) { if (rdm1.NextDouble() < mutationRate) { mutate(newPopulation.getTour(i)); } } return newPopulation; }
// Selects candidate tour for crossover private static Tour tournamentSelection(Population pop) { // Create a tournament population Population tournament = new Population(tournamentSize, false); // For each place in the tournament get a random candidate tour and // add it for (int i = 0; i < tournamentSize; i++) { int randomId = rdm1.Next(pop.populationSize()); tournament.saveTour(i, pop.getTour(randomId)); //Console.WriteLine(randomId); } // Get the fittest tour Tour fittest = tournament.getFittest(); return fittest; }