我正在为家庭作业项目研究变异算法,我很难理解为什么我在集合中得到重复项。我正在尝试使用基因突变启发式找到解决旅行蚂蚁问题(找到食物的最短路径)问题的解决方案:
private static ArrayList<Node> mutate(ArrayList<Node> mutator) {
ArrayList<Node> mutant = new ArrayList<Node>(mutator);
Collections.rotate(mutant, 1);
//Collections.shuffle(mutant, r);
for (int i = 0; i < mutant.size() - 1; i++) {
double mutantCoupleDistance = mutant.get(i).getDistanceToNext(mutant.get(i+1));
double mutatorCoupleDistance = mutator.get(i).getDistanceToNext(mutator.get(i+1));
if (mutantCoupleDistance < mutatorCoupleDistance) {
// If the mutant gene has worse "fitness" then we'll take the good gene
// from the mutator.
Node tmp = mutant.get(i);
mutant.set(i, mutator.get(i));
mutator.set(i, tmp);
tmp = mutant.get(i+1);
mutant.set(i+1, mutator.get(i+1));
mutator.set(i+1, tmp);
}
}
return
mutant;
}
我传入方法的数组是49999个元素。正如以下那样使用它:
long
startTime = System.currentTimeMillis();
do {
nodeList = mutate(nodeList);
} while (System.currentTimeMillis() - startTime < 500);
当我从mutate算法中删除交换代码时,我没有得到任何重复,这是可以理解的。但是,我很难理解为什么我在变异列表中得到重复。
节点列表开始时没有重复项。我用来报告重复的代码是以下代码:
HashSet<Node> set = new HashSet<Node>(nodeList);
if(set.size() < nodeList.size()){
System.out.println("duplicates found Set:" + set.size() + " vs. NodeList:" + nodeList.size());
}
感谢您的帮助。
答案 0 :(得分:1)
现在代码的作用是将副本旋转1.然后在某些点上,您可以交换副本中的项目和同一索引处的原始项目。然后在交换之后,您有两个相等的元素彼此相邻。例如,a b c d
和旋转后的副本d a b c
:
abcd
▲
swap here
▼
dabc
给出
aacd
dbbc
每次交换都会给出重复。代码旋转数组并重复。
从您的评论中,您可能会在Hill climbing附近使用Traveling Salesman。但是,如果你想要GA,你需要很多ArrayList<Node> mutator
或工作路径,并随机将它们组合成新的。