From 44da9e5c25a92a7ec841d38b5fc9ac0111240bc3 Mon Sep 17 00:00:00 2001 From: Sam-Armstrong Date: Sun, 5 Nov 2023 12:06:10 +0000 Subject: [PATCH] travelling salesman demo --- test_scripts/t_s_demo.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 test_scripts/t_s_demo.py diff --git a/test_scripts/t_s_demo.py b/test_scripts/t_s_demo.py new file mode 100644 index 0000000..9008641 --- /dev/null +++ b/test_scripts/t_s_demo.py @@ -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) \ No newline at end of file