gajava代码 java 代码大全( 二 )


public double selection() {
boolean[][] next_generation = new boolean[population][]; // 下一代
int length = gene_len * chrom_len;
for (int i = 0; ipopulation; i++)
next_generation[i] = new boolean[length];
double[] cumulation = new double[population];
int best_index = 0;
double max_fitness = getFitness(individuals.get(best_index));
cumulation[0] = max_fitness;
for (int i = 1; ipopulation; i++) {
double fit = getFitness(individuals.get(i));
cumulation[i] = cumulation[i - 1] + fit;
// 寻找当代的最优个体
if (fitmax_fitness) {
best_index = i;
max_fitness = fit;
}
}
Random rand = new Random(System.currentTimeMillis());
for (int i = 0; ipopulation; i++)
next_generation[i] = individuals.get(findByHalf(cumulation,
rand.nextDouble() * cumulation[population - 1]));
// 把当代的最优个体及其适应度放到best_individual中
BI bi = new BI(max_fitness, individuals.get(best_index));
// printPath(individuals.get(best_index));
//System.out.println(max_fitness);
best_individual.add(bi);
// 新一代作为当前代
for (int i = 0; ipopulation; i++)
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));

推荐阅读