gajava代码 java 代码大全

如何用Java实现遗传算法?通过遗传算法走迷宫 。虽然图1和图2均成功走出迷宫,但是图1比图2的路径长的多,且复杂 , 遗传算法可以计算出有多少种可能性,并选择其中最简洁的作为运算结果 。
示例图1:
示例图2:
实现代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* 用遗传算法走迷宫
*
* @author Orisun
*
*/
public class GA {
【gajava代码 java 代码大全】int gene_len; // 基因长度
int chrom_len; // 染色体长度
int population; // 种群大小
double cross_ratio; // 交叉率
double muta_ratio; // 变异率
int iter_limit; // 最多进化的代数
Listboolean[] individuals; // 存储当代种群的染色体
Labyrinth labyrinth;
int width;//迷宫一行有多少个格子
int height;//迷宫有多少行
public class BI {
double fitness;
boolean[] indv;
public BI(double f, boolean[] ind) {
fitness = f;
indv = ind;
}
public double getFitness() {
return fitness;
}
public boolean[] getIndv() {
return indv;
}
}
ListBI best_individual; // 存储每一代中最优秀的个体
public GA(Labyrinth labyrinth) {
this.labyrinth=labyrinth;
this.width = labyrinth.map[0].length;
this.height = labyrinth.map.length;
chrom_len = 4 * (width+height);
gene_len = 2;
population = 20;
cross_ratio = 0.83;
muta_ratio = 0.002;
iter_limit = 300;
individuals = new ArrayListboolean[](population);
best_individual = new ArrayListBI(iter_limit);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public double getCross_ratio() {
return cross_ratio;
}
public ListBI getBest_individual() {
return best_individual;
}
public Labyrinth getLabyrinth() {
return labyrinth;
}
public void setLabyrinth(Labyrinth labyrinth) {
this.labyrinth = labyrinth;
}
public void setChrom_len(int chrom_len) {
this.chrom_len = chrom_len;
}
public void setPopulation(int population) {
this.population = population;
}
public void setCross_ratio(double cross_ratio) {
this.cross_ratio = cross_ratio;
}
public void setMuta_ratio(double muta_ratio) {
this.muta_ratio = muta_ratio;
}
public void setIter_limit(int iter_limit) {
this.iter_limit = iter_limit;
}
// 初始化种群
public void initPopulation() {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; ipopulation; i++) {
int len = gene_len * chrom_len;
boolean[] ind = new boolean[len];
for (int j = 0; jlen; j++)
ind[j] = r.nextBoolean();
individuals.add(ind);
}
}
// 交叉
public void cross(boolean[] arr1, boolean[] arr2) {
Random r = new Random(System.currentTimeMillis());
int length = arr1.length;
int slice = 0;
do {
slice = r.nextInt(length);
} while (slice == 0);
if (slicelength / 2) {
for (int i = 0; islice; i++) {
boolean tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
} else {
for (int i = slice; ilength; i++) {
boolean tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}
}
// 变异
public void mutation(boolean[] individual) {
int length = individual.length;
Random r = new Random(System.currentTimeMillis());
individual[r.nextInt(length)] ^= false;
}
// 轮盘法选择下一代,并返回当代最高的适应度值

推荐阅读