gaamutation.java
来自「Java实现的遗传算法工具集:GA Playground」· Java 代码 · 共 67 行
JAVA
67 行
public class GaaMutation {
int gaType;
int mutationType;
double mutationRate;
GaaAllele alleles[];
public GaaMutation (GaaProblem problem) {
gaType = problem.gaType;
mutationType = problem.mutationType;
mutationRate = problem.mutationRate;
alleles = problem.alleles;
}
public String mutation(String chrom) {
return (mutation(chrom, mutationRate));
}
public String mutation(String chrom, double rate) {
int i, j, size;
char kar, kar2;
double n;
String st;
StringBuffer sb = new StringBuffer(chrom);
size = chrom.length();
switch (gaType) {
case 1:
for (i=0;i<size;i++) {
if (GaaMisc.flip(rate)) {
n = alleles[i].min + (double) Math.random()*(alleles[i].max-alleles[i].min);
kar = alleles[i].encodeValue(n);
sb.setCharAt(i,kar);
}
}
break;
case 2:
for (i=0;i<size;i++) {
if (GaaMisc.flip(rate)) {
j = (int) Math.floor(Math.random()*size);
Integer int1 = new Integer(i);
Integer int2 = new Integer(j);
if (!int2.equals(int1)) {
kar = sb.charAt(i);
kar2 = sb.charAt(j);
sb.setCharAt(i,kar2);
sb.setCharAt(j,kar);
}
}
}
break;
}
st = sb.toString();
return st;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?