//Our TSP internal void solveProblemTabu() { int bssfUpdates = 0; Algorithms algorithms = new Algorithms(); bssf = new TSPSolution(algorithms.greedy(Cities)); TSPSolution currentSolution = new TSPSolution(bssf.Route); int size = Convert.ToInt32(Program.MainForm.textBoxTabuSize.Text); TabuList tabuList = new TabuList(size);//set capacity of tabuList int timeSeconds = Convert.ToInt32(Program.MainForm.textBoxTime.Text); double totalTime = 0; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while(stopwatch.Elapsed.TotalSeconds < timeSeconds)//run for 600 seconds, 10 minutes { currentSolution = findBestCandidate(currentSolution, tabuList); if(currentSolution.cost < bssf.cost) { bssf = new TSPSolution(currentSolution.Route); totalTime = stopwatch.Elapsed.TotalSeconds; bssfUpdates++; } tabuList.addSolution(currentSolution); } stopwatch.Stop(); Program.MainForm.tbCostOfTour.Text = " " + bssf.cost; Program.MainForm.tbElapsedTime.Text = " " + totalTime; //Program.MainForm.tbElapsedTime.Text = " " + stopwatch.Elapsed.TotalSeconds; Program.MainForm.toolStripTextBox1.Text = " " + bssfUpdates; //print bssf update number // do a refresh. Program.MainForm.Invalidate(); }
public TSPSolution findBestCandidate(TSPSolution currentSolution, TabuList tabuList) { TSPSolution bestCandidate = null; TSPSolution candidate = new TSPSolution(new ArrayList(currentSolution.Route)); for (int swapA = 0; swapA < Cities.Length - 1; swapA++) { // only consider swapping forward so we don't double the space for (int swapB = swapA + 1; swapB < Cities.Length; swapB++) { //candidate.Route.Clear(); // perform swap City tmp = (City)candidate.Route[swapA]; candidate.Route[swapA] = candidate.Route[swapB]; candidate.Route[swapB] = tmp; // normalize to make TabuList.Contains() easier if (swapA == 0) { ArrayList normalRoute = new ArrayList(); for (int i = swapB; i < Cities.Length; i++) normalRoute.Add(candidate.Route[i]); for (int i = 0; i < swapB; i++) normalRoute.Add(candidate.Route[i]); candidate.Route = normalRoute; } // recalc cost candidate.cost = candidate.costOfRoute(); // get best candidate if (!tabuList.contains(candidate)) { if (bestCandidate == null || candidate.cost < bestCandidate.cost){ bestCandidate = new TSPSolution(new ArrayList(candidate.Route)); } } // revert swap for next candidate if (swapA == 0) { // it's simpler to recopy candidate.Route = new ArrayList(currentSolution.Route); } else { candidate.Route[swapB] = candidate.Route[swapA]; candidate.Route[swapA] = tmp; } } } if (bestCandidate == null) { tabuList.setCapacity(tabuList.capacity * 2); return tabuList.getLast(); // or whatever this function ends up being called } return bestCandidate; }