Neuron 101

Nature-inspired optimization / Travelling salesman problem

Türkçe

Plate60

Unit 6 · Topic 6 of 11

Travelling salesman problem

Medium, 8 min, 9 steps

1Istanbul2Izmir3Antalya4Ankara5Kayseri6Samsun7Erzurum8Van9Diyarbakır10Gaziantep
Keyboard: left and right arrows change the step, space plays and pauses.

Step 1 of 9 Cities

Visit each city once, return to the start

The map has 10 Turkish cities; the number inside each circle is the city's number. The salesman leaves the brass city, visits every city once and returns to where he started. The goal is the shortest total distance. Distances are straight-line distances in kilometres.

Open in Colab
  1. import math
  2. from itertools import permutations
  3. # S: 10 şehrin (x, y) konumu, km
  4. def d(a, b):
  5. return math.dist(S[a], S[b])
  6. def L(t):
  7. return sum(d(t[i - 1], t[i])
  8. for i in range(10))
  9. en_kisa = min(([0, *p] for p in
  10. permutations(range(1, 10))),
  11. key=L)
  12. tur = [6 - 1]
  13. while len(tur) < 10:
  14. kalan = [j for j in range(10)
  15. if j not in tur]
  16. tur.append(min(kalan,
  17. key=lambda j: d(tur[-1], j)))
  18. print(tur, L(tur))
  19. def ters(t, i, j):
  20. orta = t[i:j + 1][::-1]
  21. return t[:i] + orta + t[j + 1:]
  22. while True:
  23. adaylar = [ters(tur, i, j)
  24. for i in range(1, 9)
  25. for j in range(i + 1, 10)]
  26. yeni = min(adaylar, key=L)
  27. if L(yeni) > L(tur) - 1e-9:
  28. break
  29. tur = yeni
  30. print(tur, L(tur))
  31. print(L(tur) - L(en_kisa))
uzunluk
0