我需要实现一个“统一交叉”遗传算子。
编辑:我意识到如果两个人都出现一个数字,那么重复(因为随机交换)是正常的。所以我添加了这个:
if(anyDuplicate(p0_genome,minIndex) || anyDuplicate(p1_genome,minIndex)){
//rollback: swap again
swap(p0_genome,p1_genome,i);
}
但它仍然会创建重复项(大部分时间基因位于 minIndex 位置(从循环中排除!!!)。当然我测试了函数 anyDuplicate,它工作得很好
我试过这段代码
> Note: Individual 1 and 2 have the same length but a different number
> of valid bits.
>
> Foe example: genotype length (of both individuals) = 10 ,
> representation as numbers from 1 to 10 without anyone repeated,the
> start delimiter is 1 and the end delimiter should be 2. Not used genes
> are = 0
>
> individual 1(p0_genome) = {1,4,5,3,2,0,0,0,0,0}
> individual 2(p1_genome) = {1,4,6,3,8,2,0,0,0,0}
渴望输出:
Individual 1(p0_genome): **1** <some genes ALL DIFFERENTS> **2** 0,0,0,.....
Individual 2(p1_genome): **1** <some genes ALL DIFFERENTS> **2** 0,0,0,.....
主要代码:
int indexOfLastP0 = findLast(p0_genome,gl); // last valid bit (the one = 2) of first individual
int indexOfLastP1 = findLast(p1_genome,gl); // last valid bit (the one = 2) of second individual
int minIndex = Math.min(indexOfLastP0,indexOfLastP1); // last valid bit of the "smaller" of the inviduals
// Building sons
/* exchange bit without considering delimiters bit (1 and 2)
and according to the smaller individual */
int threshold = 0.60;
for (int i=1; i<minIndex; i++) {
if (Math.Random()>threshold) {
swap(p0_genome,p1_genome,i);
}
// when exiting the loop the remaining of genes remain the same
兑换码:
public void swap(int[] array1, int[] array2 ,int i){
int aux=array1[i];
if (array2[i]!=2){
array1[i]=array2[i];
}
if (aux!=2){
array2[i]=aux;
}
anyDuplicate() 代码:
public boolean anyDuplicate(int[] genoma,int min){
for (int i=0;i<=min;i++){
for (int j=0;j<=min;j++){
if (genoma[i]==genoma[j] && i!=j){
return true;
}
}
}
return false;
}
findLast 代码:
public int findLast(int[] mgenome,int genotypeLength){
int k=1; // 1 element is not considered
while (k<genotypeLength && mgenome[k]!=0){
k++;
}
return k-1; // **I also tried returning k;**
}
问题是我在两个人身上都有很多重复的数字
我还尝试了“父亲”的“重复” (从父母到孩子的数组复制):
// Creating sons genotypes
int [] s0_genome = new int[gl];
int [] s1_genome = new int[gl];
// Building sons
int threshold = 0.60;
for (int i=0; i<minIndex; i++) {
if (Math.Random()>threshold)) {
s0_genome[i] = p1_genome[i];
s1_genome[i] = p0_genome[i];
}
else {
s0_genome[i] = p0_genome[i];
s1_genome[i] = p1_genome[i];
}
for (int i=minIndex; i<10; i++) {
// copy what's left
s0_genome[i] = p0_genome[i];
s1_genome[i] = p1_genome[i];
}
难道我做错了什么?谢谢你的任何提示!