1

基于这个答案,我尝试在遗传算法中进行轮盘赌选择。

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 循环甚至一次都没有启动时吗?但是如何解决这个问题?

4

1 回答 1

0

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

所以你的循环:

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

如果返回 0 则不会运行nextInt(int bound),导致在j以下位置为 0:rouletteIndex[i] = j-1;

于 2017-01-18T10:22:16.753 回答