Java中的两点交叉

时间:2012-02-16 14:27:25

标签: java genetic-algorithm crossover

我已经实现了如下的单点交叉;

public void onePointCrossover(Individual indi) {
    if (SGA.rand.nextDouble() < pc) {

        int xoverpoint = SGA.rand.nextInt(length);


        int tmp;
        for (int i=xoverpoint; i<length; i++){
            tmp = chromosome[i];
            chromosome[i] = indi.chromosome[i];
            indi.chromosome[i] = tmp;
        }   
    }   
}

选择一点交叉 - 交叉点,从一个父项复制从染色体开始到交叉点的二进制字符串,其余字符串从第二个父项复制。

父1 =染色体,父2 = indi。

我正在把父母变成儿童。

我现在还需要进行两点交叉,但遇到一些麻烦,这是我到目前为止所做的,但我相信代码的下半部分与单点交叉相同而不是交换中间部分

       public void twoPointCrossover(Individual indi) {
        if (SGA.rand.nextDouble() < pc) {

            int xoverpoint = SGA.rand.nextInt(length);
            int xoverpoint2 = SGA.rand.nextInt(length);



            int tmp;

            if (xoverpoint > xoverpoint2){
                tmp = xoverpoint;
                xoverpoint = xoverpoint2;
                xoverpoint2 = tmp;
            }

            for (int i=xoverpoint; i<xoverpoint2; i++){
                tmp = chromosome[i];
                chromosome[i] = indi.chromosome[i];
                indi.chromosome[i] = tmp;
            }   
        }   
    }
}

这似乎不对,任何帮助都会受到如此多的赞赏!谢谢!

2 个答案:

答案 0 :(得分:1)

您应该在循环中检查i < (or <=) xoverpoint2而不是i<length

答案 1 :(得分:0)

我现在正在处理同样的问题。这是我的解决方案:

// Two-Point Crossover function
public Genome twoPtCrossover(Genome partner) {
    Genome child = new Genome(partner.genome.length);

    int crosspoint1 = xd.nextInt(genome.length);
    int crosspoint2 = xd.nextInt(genome.length);

    // Ensure crosspoints are different...
    if (crosspoint1 == crosspoint2){
        if(crosspoint1 == 0){
            crosspoint2++;
        } else {
            crosspoint1--;
        }
    }
    // .. and crosspoint1 is lower than crosspoint2
    if (crosspoint2 < crosspoint1) {
        int temp = crosspoint1;
        crosspoint1 = crosspoint2;
        crosspoint2 = temp;
    }

    for (int i = 0; i < genome.length; i++) {
        if (i < crosspoint1 || i > crosspoint2)
            child.genome[i] = genome[i];
        else
            child.genome[i] = partner.genome[i];
    }
    return child;
}