public void ApplySelection(List<IChromosome> chromosomes, int size)
{
var rand = Accord.Math.Random.Generator.Random;
// new population, initially empty
List<IChromosome> newPopulation = new List<IChromosome>();
// size of current population
int currentSize = chromosomes.Count;
// calculate summary fitness of current population
double fitnessSum = 0;
foreach (IChromosome c in chromosomes)
{
fitnessSum += c.Fitness;
}
// create wheel ranges
double[] rangeMax = new double[currentSize];
double s = 0;
int k = 0;
foreach (IChromosome c in chromosomes)
{
// cumulative normalized fitness
s += (c.Fitness / fitnessSum);
rangeMax[k++] = s;
}
// select chromosomes from old population to the new population
for (int j = 0; j < size; j++)
{
// get wheel value
double wheelValue = rand.NextDouble();
// find the chromosome for the wheel value
for (int i = 0; i < currentSize; i++)
{
if (wheelValue <= rangeMax[i])
{
// add the chromosome to the new population
newPopulation.Add(((IChromosome)chromosomes[i]).Clone());
break;
}
}
}
// empty current population
chromosomes.Clear();
// move elements from new to current population
chromosomes.AddRange(newPopulation);
}
}