java遗传算法代码 遗传算法的输入( 三 )


individuals.set(i, next_generation[i]);
return max_fitness;
}
// 折半查找
public int findByHalf(double[] arr, double find) {
if (find0 || find == 0 || findarr[arr.length - 1])
return -1;
int min = 0;
int max = arr.length - 1;
int medium = min;
do {
if (medium == (min + max) / 2)
break;
medium = (min + max) / 2;
if (arr[medium]find)
min = medium;
else if (arr[medium]find)
max = medium;
else
return medium;
} while (minmax);
return max;
}
// 计算适应度
public double getFitness(boolean[] individual) {
int length = individual.length;
// 记录当前的位置,入口点是(1,0)
int x = 1;
int y = 0;
// 根据染色体中基因的指导向前走
for (int i = 0; ilength; i++) {
boolean b1 = individual[i];
boolean b2 = individual[++i];
// 00向左走
if (b1 == falseb2 == false) {
if (x0labyrinth.map[y][x - 1] == true) {
x--;
}
}
// 01向右走
else if (b1 == falseb2 == true) {
if (x + 1widthlabyrinth.map[y][x + 1] == true) {
x++;
}
}
// 10向上走
else if (b1 == trueb2 == false) {
if (y0labyrinth.map[y - 1][x] == true) {
y--;
}
}
// 11向下走
else if (b1 == trueb2 == true) {
if (y + 1heightlabyrinth.map[y + 1][x] == true) {
y++;
}
}
}
int n = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) + 1;
//if(n==1)
//printPath(individual);
return 1.0 / n;
}
// 运行遗传算法
public boolean run() {
// 初始化种群
initPopulation();
Random rand = new Random(System.currentTimeMillis());
boolean success = false;
while (iter_limit--0) {
// 打乱种群的顺序
Collections.shuffle(individuals);
for (int i = 0; ipopulation - 1; i += 2) {
// 交叉
if (rand.nextDouble()cross_ratio) {
cross(individuals.get(i), individuals.get(i + 1));
}
// 变异
if (rand.nextDouble()muta_ratio) {
mutation(individuals.get(i));
}
}
// 种群更替
if (selection() == 1) {
success = true;
break;
}
}
return success;
}
//public static void main(String[] args) {
//GA ga = new GA(8, 8);
//if (!ga.run()) {
//System.out.println("没有找到走出迷宫的路径.");
//} else {
//int gen = ga.best_individual.size();
//boolean[] individual = ga.best_individual.get(gen - 1).indv;
//System.out.println(ga.getPath(individual));
//}
//}
// 根据染色体打印走法
public String getPath(boolean[] individual) {
int length = individual.length;
int x = 1;
int y = 0;
LinkedListString stack=new LinkedListString();
for (int i = 0; ilength; i++) {
boolean b1 = individual[i];
boolean b2 = individual[++i];
if (b1 == falseb2 == false) {
if (x0labyrinth.map[y][x - 1] == true) {
x--;
if(!stack.isEmpty()stack.peek()=="右")
stack.poll();
else
stack.push("左");
}
} else if (b1 == falseb2 == true) {
if (x + 1widthlabyrinth.map[y][x + 1] == true) {
x++;
if(!stack.isEmpty()stack.peek()=="左")
stack.poll();
else
stack.push("右");
}
} else if (b1 == trueb2 == false) {
if (y0labyrinth.map[y - 1][x] == true) {
y--;
if(!stack.isEmpty()stack.peek()=="下")
stack.poll();
else
stack.push("上");
}
} else if (b1 == trueb2 == true) {
if (y + 1heightlabyrinth.map[y + 1][x] == true) {
y++;
if(!stack.isEmpty()stack.peek()=="上")
stack.poll();
else
stack.push("下");
}
}
}
StringBuilder sb=new StringBuilder(length/4);

推荐阅读