Hello,
I'm trying to code a genetic algorithm in java but my code doesn't seem to be working as it should.
I think the problem lies within my roulette wheel selection method.
Can anyone spot it/point me in the right direction on how to solve it?

    private static Individual[] rouletteWheelSelection2(Individual[] aPopulation) {

        Random random = new Random();
        Individual[] populationNew = new Individual[popSize];
        int totalFitness = 0;

        //sum the total fitness of the population
        for (int i = 0; i < popSize; i++) {
            Individual currentIndividual = aPopulation[i];
            totalFitness += currentIndividual.fitnessVal;
        }


        /* sum the fitness of each individual in the population again
         * until the running sum is >= to the randomly chosen number. 
         */

        for (int i = 0; i < popSize; i++) {

            //pick a random number between 0 and that sum.
            int randomNumber = random.nextInt(totalFitness + 1);

            int runningSum = 0;
            int index = 0;
            int lastAddedIndex = 0;
            while (runningSum < randomNumber) {
                runningSum += aPopulation[index].fitnessVal;
                lastAddedIndex = index;
                index++;
            }

            populationNew[i] = aPopulation[lastAddedIndex];
            runningSum = 0;
            index = 0;
            lastAddedIndex = 0;
        }

        return populationNew;
    }

Also, once you've selected the first parent, do you have to remove it from the original population? Because otherwise that leaves an opportunity for the parent to mate with itself, which seems illogical.

I don't exactly understand what you're trying to do here. What do you mean when you say "Genetic algorithm" and what is the purpose of the method rouletteWheelSelection2(Individual[] aPopulation)? It is returning the population, but changed. I think you may need to provide more information or more code (It would be better with both)

It wouldn't matter if after you selected the parent if you want to remove it you can, or you can check if the same person before continuing

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.