Accord.Genetic.RankSelection.ApplySelection C# (CSharp) Method

ApplySelection() public method

Apply selection to the specified population.
Filters specified population keeping only those chromosomes, which won "roulette" game.
public ApplySelection ( List chromosomes, int size ) : void
chromosomes List Population, which should be filtered.
size int The amount of chromosomes to keep.
return void
        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;

            // sort current population
            chromosomes.Sort();

            // calculate amount of ranges in the wheel
            double ranges = currentSize * (currentSize + 1) / 2;

            // create wheel ranges
            double[] rangeMax = new double[currentSize];
            double s = 0;

            for (int i = 0, n = currentSize; i < currentSize; i++, n--)
            {
                s += ((double)n / ranges);
                rangeMax[i] = 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);
        }
    }