Tsp遗传算法代码非常好
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package GA;
import java.util.*;
public class Tsp {
private String cityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","郑州","西安","兰州","银川","西宁","乌鲁木齐","合肥","南京","杭州","长沙","南昌","武汉","成都","贵州","福建","台北","广州","海口","南宁","昆明","拉萨","香港","澳门"};
//private String cityEnd[]=new String[34];
private int cityNum=cityName.length; //城市个数
private int popSize = 50; //种群数量
private int maxgens = 20000; //迭代次数
private double pxover = 0.8; //交叉概率
private double pmultation = 0.05; //变异概率
private long[][] distance = new long[cityNum][cityNum];
private int range = 2000; //用于判断何时停止的数组区间
private class genotype {
int city[] = new int[cityNum]; //单个基因的城市序列
long fitness; //该基因的适应度
double selectP; //选择概率
double exceptp; //期望概率
int isSelected; //是否被选择
}
private genotype[] citys = new genotype[popSize];
/**
* 构造函数,初始化种群
*/
public Tsp() {
for (int i = 0; i < popSize; i++) {
citys[i] = new genotype();
int[] num = new int[cityNum];
for (int j = 0; j < cityNum; j++)
num[j] = j;
int temp = cityNum;
for (int j = 0; j < cityNum; j++) {
int r = (int) (Math.random() * temp);
citys[i].city[j] = num[r];
num[r] = num[temp - 1];
temp--;
}
citys[i].fitness = 0;
citys[i].selectP = 0;
citys[i].exceptp = 0;
citys[i].isSelected = 0;
}
initDistance();
}
/**
* 计算每个种群每个基因个体的适应度,选择概率,期望概率,和是否被选择。 */
public void CalAll(){
for( int i = 0; i< popSize; i++){
citys[i].fitness = 0;
citys[i].selectP = 0;
citys[i].exceptp = 0;
citys[i].isSelected = 0;
}
CalFitness();
CalSelectP();
CalExceptP();
CalIsSelected();
}
/**
* 填充,将多选的填充到未选的个体当中
*/
public void pad(){
int best = 0;
int bad = 0;
while(true){
while(citys[best].isSelected <= 1 && best while(citys[bad].isSelected != 0 && bad bad ++; for(int i = 0; i< cityNum; i++) citys[bad].city[i] = citys[best].city[i]; citys[best].isSelected --; citys[bad].isSelected ++; bad ++; if(best == popSize ||bad == popSize) break; } } /** * 交叉主体函数 */ public void crossover() { int x; int y; int pop = (int)(popSize* pxover /2); while(pop>0){ x = (int)(Math.random()*popSize); y = (int)(Math.random()*popSize); executeCrossover(x,y);//x y 两个体执行交叉 pop--; } } /** * 执行交叉函数 * @param个体x * @param个体y * 对个体x和个体y执行佳点集的交叉,从而产生下一代城市序列 */ private void executeCrossover(int x,int y){ int dimension = 0; for( int i = 0 ;i < cityNum; i++) if(citys[x].city[i] != citys[y].city[i]){ dimension ++; } int diffItem = 0; double[] diff = new double[dimension]; for( int i = 0 ;i < cityNum; i++){ if(citys[x].city[i] != citys[y].city[i]){ diff[diffItem] = citys[x].city[i]; citys[x].city[i] = -1; citys[y].city[i] = -1; diffItem ++; } } Arrays.sort(diff); double[] temp = new double[dimension]; temp = gp(x, dimension);