20231010-遗传算法解旅行商问题-优化

main
HYChan 2 years ago
parent 9f898444ce
commit 1b48f7d07f

@ -6,12 +6,12 @@ public class TSP {
private static int city_num=30;//每个种群里的城市数量
private static int iterative=500;//迭代500代
private static double[]possible;
private static double[][]city={{ -0.07, 0.60 }, { 0.86, 0.17 }, { 0.94, -0.49 }, { 0.69, -0.54 },
{ 0.66, -0.15 }, { 0.39, 0.67 }, { 0.87, 0.08 }, { -0.97, 0.92 }, { 0.81, 0.03 }, { -0.41, 0.82 },
{ 0.10, -0.29 }, { -0.22, -0.66 }, { 0.74, -0.95 }, { -0.09, -0.24 }, { 0.93, 0.55 }, { 0.86, 0.66 },
{ -0.67, 0.80 }, { 0.14, -0.23 }, { -0.64, 0.34 }, { -0.38, -0.08 }, { -0.82, -0.75 }, { 0.40, 0.82 },
{ 0.56, 0.34 }, { -0.76, -0.08 }, { 0.78, -0.22 }, { -0.60, -0.81 }, { 0.41, -0.76 }, { 0.81, 0.52 },
{ 0.92, 0.97 }, { -0.13, -0.24 }};//城市坐标
private static double[][]city={{ -0.05, 0.85 }, { 0.76, 0.37 }, { 0.34, -0.89 }, { 0.69, -0.54 },
{ 0.26, -0.45 }, { 0.32, 0.57 }, { 0.57, 0.88 }, { -0.57, 0.82 }, { 0.71, 0.05 }, { -0.61, 0.72 },
{ 0.10, -0.29 }, { -0.22, -0.66 }, { 0.74, -0.95 }, { -0.09, -0.24 }, { 0.93, 0.55 }, { 0.36, 0.56 },
{ -0.35, 0.81 }, { 0.14, -0.23 }, { -0.54, 0.94 }, { -0.38, -0.08 }, { -0.82, -0.75 }, { 0.40, 0.82 },
{ 0.86, 0.54 }, { -0.67, -0.18 }, { 0.76, -0.32 }, { -0.60, -0.81 }, { 0.41, -0.76 }, { 0.81, 0.52 },
{ 0.82, 0.77 }, { -0.14, -0.35 }};//城市坐标
//【*入口函数TSP整体算法主体】
public static void main(String[] args) throws Exception {
@ -31,13 +31,14 @@ public class TSP {
possible=cal_possible(sample);
sample=select(sample);
best=find_best(sample);
best=find_the_best(sample);
System.out.println();
System.out.println(String.format("【-----第%d代-----】", i+1));
System.out.println(String.format("【适应度最大值】%f", best.fitness));
System.out.println(String.format("【路程最小值】%f", 1/best.fitness));
System.out.println();
}
}
@ -81,7 +82,7 @@ public class TSP {
}
//【*辅助方法:挑选父个体】
static CityPoint sel_father(ArrayList<CityPoint>father_group){
static CityPoint select_father(ArrayList<CityPoint>father_group){
Random random =new Random();
double t =random.nextDouble();//随机生成一个0到1之间的浮点数t用来与个体被抽中的概率进行比较
int i;//这个i之后也被当成索引用
@ -94,8 +95,8 @@ public class TSP {
}
//【*辅助方法:繁殖,获得子代】
static CityPoint get_child(ArrayList<CityPoint>father_group){
CityPoint parentA=sel_father(father_group);//从父种群中挑出一个父个体
CityPoint parentB=sel_father(father_group);//从父种群中挑出第二个父个体
CityPoint parentA=select_father(father_group);//从父种群中挑出一个父个体
CityPoint parentB=select_father(father_group);//从父种群中挑出第二个父个体
int[]tmp=new int[city_num];//创建一个长度为个体元素数的数组30
Random random=new Random();
int indexA;//定义两个指数,作为两个父个体的交换点
@ -166,7 +167,7 @@ public class TSP {
}
//【*主方法:判断当前最优值】
static CityPoint find_best(ArrayList<CityPoint>group){
static CityPoint find_the_best(ArrayList<CityPoint>group){
CityPoint best=group.get(0);//暂时将数组中的第一个元素视作最优解
for(CityPoint group_indi:group){//遍历传入的数组
if(group_indi.fitness>best.fitness)//每次遍历到的个体都和当前的最优解做比较,如果当前遍历的种群个体适应度>当前最优解的适应度

Loading…
Cancel
Save