FitnessProportionateSelectionOperator extends AbstractProportionateSelectionOperator { protected List<Individual> selectWinners(Individual[] inputIndividuals, double[] accumulatedProbabilities){ int resultSize = this.outputArity * this.individualsPerPopulation; List<Individual> resultingIndividuals = new ArrayList<Individual>(resultSize); for (int i = 0; i < resultSize; i++){ double probability = this.randomGenerator.nextRandom(); for (int j = 0; j < inputIndividuals.length; j++){ if (accumulatedProbabilities[j] >= probability){ resultingIndividuals.add(inputIndividuals[j]); break; } } } return resultingIndividuals; }    }
@Test public void testSelectWinners() throws Exception { this.operator.setIndividualsPerPopulation(5); this.operator.setOutputArity(1); this.operator.setInputArity(1); this.operator.setRandomGenerator(new EmptyRandomGenerator(){ double[] numbers = new double[]{10.0/15, 11.0/15, 7.5/15, 8.0/15, 9.0/15}; int index = 0; @Override public double nextRandom() { return numbers[index++]; } }); Individual[] inputIndividuals = new Individual[5]; double[] fitness = new double[]{2.0, 4.0, 1.0, 5.0, 3.0}; for (int i = 0; i < 5; i++){ inputIndividuals[i] = new SimpleIndividual(1, 1.0, new SimplePhenotypeRepresentation()); inputIndividuals[i].setFitness(fitness[i]); } double[] accumulatedProbabilities = this.operator.makeAccumulatedProbabilities(inputIndividuals); assertTrue(accumulatedProbabilities.length == 5); assertTrue(accumulatedProbabilities[0] == (2.0/15)); assertTrue(accumulatedProbabilities[1] == (6.0/15)); assertTrue(accumulatedProbabilities[2] == (7.0/15)); assertTrue(accumulatedProbabilities[3] == (12.0/15)); assertTrue(accumulatedProbabilities[4] == 1.0); List<Individual> winners = this.operator.selectWinners(inputIndividuals, accumulatedProbabilities); assertEquals(5, winners.size()); assertTrue(inputIndividuals[3].getFitness() == 5.0); for (Individual individual : winners){ assertTrue(individual.getFitness() == 5.0); } }