-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalSearchSolver.cpp
80 lines (54 loc) · 2.06 KB
/
LocalSearchSolver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @file TSPSolver.cpp
* @brief TSP solver (neighborhood search)
*/
#include "LocalSearchSolver.h"
#include <iostream>
std::string LocalSearchSolver::getSolverName() const {
return string("Local Search ") + findNeighbor->getName();
}
bool LocalSearchSolver::solve( const TSP& tsp , const TSPSolution& initSol , TSPSolution& bestSol ) {
try {
bool stop = false;
int iter = 0;
TSPSolution currSol(initSol);
double bestValue, currValue;
bestValue = currValue = currSol.evaluateObjectiveFunction(tsp);
TSPMove move;
while (!stop) {
if ( tsp.n < 20 ) {
currSol.print(std::cout); //log current solution (only small instances)
}
std::cout << " (" << ++iter << ") value " << currValue << " (" << bestValue << ")";
// first improvement
// neigh = findFirstBestNeighbor(tsp, currSol, )
// neighValue = compute neight obj fun value
// if neighValue < currentBest then bestFound = currentBest = neightValue
// incremental evaluation: findBestNeighbour returns the cost increment
double bestNeighValue = currValue + findNeighbor->execute(tsp, currSol, move);
std::cout << "\t move: " << move.from << " , " << move.to << std::endl;
// stop criteria
if (bestNeighValue < currValue) {
bestValue = currValue = bestNeighValue;
currSol = swap(currSol,move);
}
else {
stop = true; // exit from cycle
}
}
bestSol = currSol;
bestSol.iterations = iter;
}
catch (std::exception& e) {
std::cout << ">>>EXCEPTION: " << e.what() << std::endl;
return false;
}
return true;
}
TSPSolution& LocalSearchSolver::swap( TSPSolution& tspSol , const TSPMove& move ) {
TSPSolution tmpSol(tspSol);
for (int i = move.from ; i <= move.to ; ++i) {
tspSol.sequence[i] = tmpSol.sequence[move.to-(i-move.from)];
}
return tspSol;
}