GA中的轮盘赌轮选择:ArrayIndexOutOfBoundsException错误

时间:2017-01-18 10:09:27

标签: java algorithm generics selection roulette-wheel-selection

基于this answer我试图在遗传算法中选择轮盘赌。

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;
}

之后我得到:

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

“ - 1”?但是,当j应该总是大于0时如何。 当numberRand = 0并且while循环甚至没有启动一次时会发生这种情况吗?但是如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

Random.nextInt(int bound)返回0(含)到指定的边界(不包括)。

所以你的循环:

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

如果nextInt(int bound)返回0,则无法运行,导致j为0:rouletteIndex[i] = j-1;