private void GenerateNextPopulation() { Random rnd = new Random(); Chromosome oldBestSolution = new Chromosome(ProblemParameters.Dimension); Chromosome newBestSolution, newWrostSolution; // Store best found solution _bestOfCurrentPopulation.CopyTo(oldBestSolution); // #region Selection (Algorithm: Tournament) int tourSize; // Tournament size int bestChromosomeIndex = 0; double bestFitness; if (PopulationSize < 32) { tourSize = 3; } else { tourSize = (int)Math.Log(PopulationSize, 2) - 1; } for (int i = 0; i < PopulationSize; i++) { bestFitness = Double.NegativeInfinity; for (int j = 0; j < tourSize; j++) { int rndIndex; rndIndex = rnd.Next(PopulationSize); if (_currentPopulation[rndIndex].FitnessValue > bestFitness) { bestFitness = _currentPopulation[rndIndex].FitnessValue; bestChromosomeIndex = rndIndex; } } // Copy the "winner of tournament" to Intermediate Population _currentPopulation[bestChromosomeIndex].CopyTo(_intermediatePopulation[i]); } #endregion #region Crossover (Algorithm: Arithmetic Crossover) for (int i = 0; i < PopulationSize / 2; i++) { if (rnd.NextDouble() < ProbabilityOfCrossover) { // Do Crossover Chromosome.DoCrossover(_intermediatePopulation[i], _intermediatePopulation[i + 1], _currentPopulation[i], _currentPopulation[i + 1]); } else { // Do NOT Crossover (Copy parents to the new population without any change) _intermediatePopulation[i].CopyTo(_currentPopulation[i]); _intermediatePopulation[i + 1].CopyTo(_currentPopulation[i + 1]); } } #endregion #region Mutation newBestSolution = newWrostSolution = _currentPopulation[0]; for (int i = 0; i < PopulationSize; i++) { if (rnd.NextDouble() < ProbabilityOfMutation) { _currentPopulation[i].DoMutation(); } // Find wrost of this (new) population if (_currentPopulation[i].FitnessValue < newWrostSolution.FitnessValue) { newWrostSolution = _currentPopulation[i]; } // Find best of this (new) population if (_currentPopulation[i].FitnessValue > newBestSolution.FitnessValue) { newBestSolution = _currentPopulation[i]; } } #region Elitism oldBestSolution.CopyTo(newWrostSolution); // After this statement, "newWrostSolution" will point to "Old Best Solution"! // Now we must find best of current and old populations _bestOfCurrentPopulation = (oldBestSolution.FitnessValue < newBestSolution.FitnessValue) ? newBestSolution : newWrostSolution; #endregion #endregion }