Java 遗传算法,旅行商问题
在交叉过程中,我在课堂上做项目时遇到了一些问题,我理解我在作业后面会遇到的问题,但教授问我的1号染色体和2号染色体是如何报告的Java 遗传算法,旅行商问题,java,arraylist,genetic-algorithm,traveling-salesman,Java,Arraylist,Genetic Algorithm,Traveling Salesman,在交叉过程中,我在课堂上做项目时遇到了一些问题,我理解我在作业后面会遇到的问题,但教授问我的1号染色体和2号染色体是如何报告的 randomNum = rand.nextInt(3); Chromosome chromosome2 = topTen.remove(randomNum); System.out.print(chromosome2 + "\n"); index = generation.indexOf(chromosome2); generation.remove(index);
randomNum = rand.nextInt(3);
Chromosome chromosome2 = topTen.remove(randomNum);
System.out.print(chromosome2 + "\n");
index = generation.indexOf(chromosome2);
generation.remove(index);
下面是代码的其余部分
public Chromosome tsp(int population, int num_generations) {
//Random Seed
Random rand = new Random();
int randomNum;
//Generate inital population
ArrayList<Chromosome> generation = new ArrayList<Chromosome>();
for (int i = 0; i < population; i++) {
//Clone original
ArrayList<Vertex> genes = new ArrayList<Vertex>();
for (Vertex v: vertex_list) {
genes.add(new Vertex(v.toString()));
}
//Mix genes
for (int j = genes.size() - 1; j > 1; j--) {
randomNum = rand.nextInt(j) + 1;
Vertex removed = genes.remove(randomNum);
genes.add(removed);
}
genes.add(genes.get(0)); //Add start gene to end
int score = checkScore(genes); //Check distance
Chromosome chromosome = new Chromosome(genes, score); //Create chromosome
generation.add(chromosome); //Add chromosome to generation list
}
//Generation Loop
for (int i = 0; i < num_generations; i++) {
ArrayList<Chromosome> newGen = new ArrayList<Chromosome>(); //Holds new generation
Collections.sort(generation); //Sort generation
//Keep top 10 from previous generation
for (int j = 0; j < 10; j++) {
Chromosome best = generation.remove(j);
newGen.add(best);
}
//Crossover the rest of the generation
while(!generation.isEmpty()) {
//Pick Ten Randomly
ArrayList<Chromosome> topTen = new ArrayList<Chromosome>();
for (int j = 0; j < 10; j++) {
randomNum = rand.nextInt(generation.size());
topTen.add(generation.get(randomNum));
}
//Sort Those 10
Collections.sort(topTen);
//Get first chromosome
randomNum = rand.nextInt(4);
Chromosome chromosome1 = topTen.remove(randomNum);
System.out.print(chromosome1 + "\n");
int index = generation.indexOf(chromosome1);
generation.remove(index); //remove extra
//Get second chromosome
randomNum = rand.nextInt(3);
Chromosome chromosome2 = topTen.remove(randomNum);
System.out.print(chromosome2 + "\n");
index = generation.indexOf(chromosome2);
generation.remove(index); //remove extra
}
}
return generation.get(0);
}
染色体类构造器
public Chromosome(ArrayList<Vertex> genes, int score) {
this.genes = genes;
this.score = score;
}
我发现了我的问题。在随机产生10条染色体的过程中添加了重复的染色体。只需要让它们独一无二。genes.addgenes.get0//将开始基因添加到结束整数分数=checkScoregenes//检查染色体距离=新染色体,得分//创建染色体生成。添加染色体//使用此处的格式将有问题的代码添加到生成列表中。不要在注释中发布代码。你可以修改你的问题。编辑你的帖子,而不是写评论-好的,我编辑了这篇帖子。我会记住这一点,以备将来发布。谢谢