1

Based on this answer I've tried to do my roulette wheel selection in genetic algorithm.

private static final int NUMBER_OF_TOURISTS = 20;

private static int[] roulette(int population[]) {
    int sumProb = 0;
    for (int i = 0; i < population.length; i++) {
        sumProb += population[i];
    }

    int[] rouletteIndex = new int[NUMBER_OF_TOURISTS];
    Random r = new Random();
    for (int i = 0; i < NUMBER_OF_TOURISTS; i++) {
        int numberRand = r.nextInt(sumProb);
//-------------------------------------------------------
        int j = 0;          
        while (numberRand > 0) {
            numberRand = numberRand - population[j];
            j++;
        }
        rouletteIndex[i] = j-1;
//-------------------------------------------------------
    }
    return rouletteIndex;
}

after this I get:

[6, 2, -1, 19, 13, 2, 14, 2, 6, 19, 7, 14, 18, 0, 1, 9, 13, 10, 7, 2]

"-1"? But how, when j should be always greater than 0. Is this happen when numberRand = 0 and than while loop doesn't start even once? But how to fix this?

Community
  • 1
  • 1
Peter Claw
  • 21
  • 2

1 Answers1

0

Random.nextInt(int bound) returns 0 (inclusive) to specified bound (exclusive).

So your loop:

while (numberRand > 0) {
    numberRand = numberRand - population[j];
    j++;
}

Will not run if nextInt(int bound) returns 0, resulting in j being 0 at: rouletteIndex[i] = j-1;

d.j.brown
  • 1,822
  • 1
  • 12
  • 14
  • Like I thought. I do simply: only if (j > 0) than j = j-1; else j = 0 – Peter Claw Jan 18 '17 at 11:12
  • Well inaccordance with the answer you linked your implementation makes sense. But the pseuocode doesn't make it clear what should happen when `r = 0`. I would suggest `rouletteIndex[i] = j == 0 ? 0 : j - 1;` as a quick fix. – d.j.brown Jan 18 '17 at 12:42