From 89c64fbc3f8b5df1c13426b996c373b8fb625748 Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Tue, 20 Apr 2021 04:39:11 +0000 Subject: working BruteForce --- src/CS340.TSP/TSP.cs | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) (limited to 'src/CS340.TSP/TSP.cs') diff --git a/src/CS340.TSP/TSP.cs b/src/CS340.TSP/TSP.cs index a37ab3d..e4306e9 100644 --- a/src/CS340.TSP/TSP.cs +++ b/src/CS340.TSP/TSP.cs @@ -15,7 +15,7 @@ namespace TSP public static Tour BruteForce(Graph map, int init) { - + Map = map; Tour intialTour = new Tour(map.Vertices); GenerateTour(intialTour[init], new Tour(map.Vertices), new Tour()); @@ -25,30 +25,31 @@ namespace TSP static void GenerateTour(City city, Tour tour, Tour visited) { // create local copy of Tour variables - Tour currTour = tour.DeepCopy(); - Tour currVisited = visited.DeepCopy(); + Tour currTour = new Tour(tour.Cities); + Tour currVisited = new Tour(visited.Cities); + City currCity = new City(city); // remove current City from tour - bool removed = currTour.Cities.Remove(city); + currTour.Cities.RemoveAt(currTour.Cities.FindIndex(city => city.Id == currCity.Id)); //? verify that city was removed - Debug.Assert(removed, - $"Failed to remove a city from the tour. \nTour: {tour}\nCity: {city.Id}"); + Debug.Assert(currVisited.Cities.Find(city => city.Id == currCity.Id) == null, + $"Failed to remove a city from the tour. \nTour: {tour}\nCity: {currCity.Id}"); // add current City to visited if (currVisited.Cities.Count > 0) { - city.Parent = currVisited.Cities.Last().Id; - city.Key = Map.Vertices[city.Id].Edges - .Where(edge => edge.V == city.Parent) + currCity.Parent = currVisited.Cities.Last().Id; + currCity.Key = Map.Vertices[currCity.Id].Edges + .Where(edge => edge.V == currCity.Parent) .Last().Weight; } - currVisited.Cities.Add(city); + currVisited.Cities.Add(currCity); //? verify that city was added - Debug.Assert(currVisited.Cities.Contains(city), - $"Failed to add a city to the tour. \nTour: {tour}\nCity: {city.Id}"); + Debug.Assert(currVisited.Cities.Find(city => city.Id == currCity.Id) != null, + $"Failed to add a city to the tour. \nTour: {tour}\nCity: {currCity.Id}"); // loop through each city. Each level of recursion has a one less city in currTour.Cities // leaving the base case @@ -61,7 +62,7 @@ namespace TSP currVisited.Cities.First().Parent = currVisited.Cities.Last().Id; if (BestTour == null || currVisited.Weight < BestTour.Weight) - BestTour = currVisited.DeepCopy(); + BestTour = new Tour(currVisited.Cities); // Debug.Print($"{currTour}"); } -- cgit v1.2.3-70-g09d2