【问题标题】:Roulette wheel selection in GA: ArrayIndexOutOfBoundsException errorGA 中的轮盘选择:ArrayIndexOutOfBoundsException 错误
【发布时间】:2017-01-18 10:09:27
【问题描述】:

基于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 循环甚至没有启动一次时会发生这种情况吗?但是如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

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

    所以你的循环:

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

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

    【讨论】:

    • 就像我想的那样。我做的很简单:只有当 (j > 0) 比 j = j-1;否则 j = 0
    • 好吧,根据您链接实施的答案是有道理的。但是伪代码并没有明确说明r = 0 时应该发生什么。我建议将rouletteIndex[i] = j == 0 ? 0 : j - 1; 作为快速解决方案。
    猜你喜欢
    • 2018-07-04
    • 2021-06-02
    • 2013-06-19
    • 2014-08-27
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2010-09-22
    相关资源
    最近更新 更多