Ejemplo n.º 1
0
        public static Chromosome[] rouletteSelect(Chromosome[] population, int numToSelect)
        {
            Chromosome[] toReturn = new Chromosome[numToSelect];
            int[] popIndex = new int[population.Length];
            bool[] hasBeenSelected = new bool[population.Length];

            // sort and compute total fitness
            int fitnessSum = 0;
            population = population.OrderByDescending(x => x.getFitnessScore()).ToArray();
            int previousFitness = 0;
            int counter = 0;
            foreach (Chromosome chrome in population)
            {
                popIndex[counter] = chrome.getFitnessScore() + previousFitness;
                previousFitness = popIndex[counter];
                counter++;
                fitnessSum += chrome.getFitnessScore();
            }

            int selected;
            for(int i = 0; i < numToSelect; i++)
            {
                selected = Program.rng.Next(fitnessSum);
                int index = 0;
                while (selected >= popIndex[index])
                {
                    index++;
                }
                // chrome @ current index was selected from the roulette
                // if the chromosome has already been selected, we just randomly
                // generate another number. This is an easy way to do this but
                // can potentially take a long time to finish the selection if
                // the proportion of selected to not selected is high.
                if (!hasBeenSelected[index])
                {
                    toReturn[i] = population[index];
                    hasBeenSelected[index] = true;
                }
                else
                {
                    // we don't want to go to the next index since we tried
                    // to select something already selected
                    i--;
                }
            }
            return toReturn;
        }