Skip to content

Commit 6e66d00

Browse files
authored
Merge pull request #1 from Nickit1050/patch-1
Fix some problems and improve the 2-opt TSP
2 parents 6afc774 + 397dd29 commit 6e66d00

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

2-opt-tsp/2-opt-tsp.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,30 +15,36 @@ def calculateWeight(self, tour):
1515
ret = 0
1616
for idx in range(len(tour)):
1717
v_1 = tour[idx]
18-
if idx == len(tour)-1:
19-
v_2 = tour[0]
20-
else:
21-
v_2 = tour[idx+1]
18+
v_2 = tour[(idx+1)%len(tour)]
2219
ret += self.weights[v_1][v_2]
2320
return ret
2421

2522
# optimize
2623
def optimize(self):
2724
N = len(self.tour)
28-
for i in range(N-3):
29-
for j in range(i+2, N-1):
25+
# use heuristic for calculating the best local minimum
26+
bestTour = self.tour
27+
bestD = self.d
28+
for i in range(N-2):
29+
for j in range(i+2, N):
3030
newTour = np.copy(self.tour)
31-
newTour[i+1] = self.tour[j]
31+
newTour[(i+1)%N] = self.tour[j%N]
3232
tmp = i+2
3333
for k in range(j-1, i, -1):
34-
newTour[tmp] = self.tour[k]
34+
newTour[tmp%N] = self.tour[k%N]
3535
tmp += 1
3636
newD = self.calculateWeight(newTour)
37-
if newD < self.d:
38-
self.tour = np.copy(newTour)
39-
self.d = newD
40-
print(f"Tour: {self.printTour(self.tour)}, total distance: {self.d}")
41-
self.optimize() # tail recursive
37+
if newD < bestD:
38+
bestTour = np.copy(newTour)
39+
bestD = newD
40+
41+
if self.d == bestD:
42+
return
43+
44+
self.tour = bestTour
45+
self.d = bestD
46+
print(f"Tour: {self.printTour(self.tour)}, total distance: {self.d}")
47+
self.optimize() # tail recursive
4248

4349
# map a list of integers to the corresponding list of strings
4450
def printTour(self, tour):
@@ -110,4 +116,4 @@ def preorder(self, root):
110116

111117

112118

113-
119+

0 commit comments

Comments
 (0)