Tour finalTour = new Tour();
for (int x = 0; x < 10; x++) {
Tour t = new Tour(cityArray);
t.shuffle();
if (finalTour.getTourDistance() == 0.0 || (t.getTourDistance() < finalTour.getTourDistance())) {
finalTour = t;
}
System.out.print("T" + x + ": " + t.getTourDistance());
System.out.println(" finalTour: " + finalTour.getTourDistance());
}
这里是示例输出:
T0: 5.23606797749979 finalTour: 5.23606797749979
T1: 4.0 finalTour: 4.0
T2: 5.446461113496085 finalTour: 5.446461113496085
T3: 6.06449510224598 finalTour: 6.06449510224598
T4: 4.0 finalTour: 4.0
T5: 4.0 finalTour: 4.0
T6: 4.618033988749895 finalTour: 4.618033988749895
T7: 4.82842712474619 finalTour: 4.82842712474619
T8: 4.618033988749895 finalTour: 4.618033988749895
T9: 5.03224755112299 finalTour: 5.03224755112299
我的getTourDistance方法返回总城市数组的欧几里德距离。请注意,我没有静态类或方法......
public double getTourDistance() {
double totalDistance = 0.0;
if (this.tour.size() > 0) {
for (int x = 0; x < this.tour.size() - 1; x++) {
totalDistance += Math.sqrt(Math.pow((this.tour.get(x + 1).getY() - this.tour.get(x).getY()), 2) + Math.pow((this.tour.get(x + 1).getX() - this.tour.get(x).getX()),2));
}
totalDistance += Math.sqrt(Math.pow((this.tour.get(0).getY() - this.tour.get(this.tour.size() - 1).getY()), 2) + Math.pow((this.tour.get(0).getX() - this.tour.get(this.tour.size() - 1).getX()),2));
}
return totalDistance;
}