java遗传算法:仅在基因型的一部分中进行均匀交叉
我需要实现一个“均匀交叉”遗传算子
编辑:我意识到,如果一个数字同时出现在两个人身上,那么出现重复的数字(因为随机交换)是正常的。 所以我补充说:
if(anyDuplicate(p0_genome,minIndex) || anyDuplicate(p1_genome,minIndex)){
//rollback: swap again
swap(p0_genome,p1_genome,i);
}
但它仍然会产生重复(大多数情况下,位于minIndex位置的基因(被排除在循环之外!!!)。当然,我测试了这个函数,它运行得非常好
我用这个密码试过了
> 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;**
}
问题是,我在两个人身上都得到了很多重复的数字
我还尝试了“父亲”的“复制”(从父母到孩子的arraycopy):
// 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];
}
我做错什么了吗?谢谢你的提示
共 (0) 个答案