Skip to content

Commit

Permalink
travelling salesman demo
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam-Armstrong committed Nov 5, 2023
1 parent 79931dd commit 44da9e5
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions test_scripts/t_s_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import numpy as np

def nearest_neighbor_tsp(cities):
num_cities = len(cities)
if num_cities < 2:
return cities

# Initialize variables
unvisited_cities = set(range(num_cities))
tour = [0] # Start with the first city as the initial city
current_city = 0

while unvisited_cities:
nearest_city = min(unvisited_cities, key=lambda city: np.linalg.norm(cities[current_city] - cities[city]))
tour.append(nearest_city)
current_city = nearest_city
unvisited_cities.remove(nearest_city)

# Return to the starting city to complete the tour
tour.append(tour[0])

return [cities[i] for i in tour]

# Example usage:
cities = np.array([[0, 0], [2, 4], [3, 1], [5, 3], [6, 5]])
optimal_tour = nearest_neighbor_tsp(cities)

0 comments on commit 44da9e5

Please sign in to comment.