-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTSPSolution.h
116 lines (87 loc) · 2.51 KB
/
TSPSolution.h
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* @file TSPSolution.h
* @brief TSP solution
*
*/
#ifndef TSPSOLUTION_H
#define TSPSOLUTION_H
#include <vector>
#include <cmath>
#include "TSP.h"
/**
* TSP Solution representation: ordered sequence of nodes (path representation)
*/
class TSPSolution
{
public:
std::vector<int> sequence;
// utils solutions fields
std::string solveBy;
double userTime;
double cpuTime;
uint iterations;
TSPSolution( const TSP& tsp ) {
sequence.reserve(tsp.n + 1);
for ( int i = 0; i < tsp.n ; ++i ) {
sequence.push_back(i);
}
sequence.push_back(0);
solveBy = "Random";
userTime = -1.0;
cpuTime = -1.0;
iterations = 0;
}
TSPSolution( const TSPSolution& tspSol ) {
sequence.reserve(tspSol.sequence.size());
for (uint i = 0; i < tspSol.sequence.size(); ++i ) {
sequence.push_back(tspSol.sequence[i]);
}
solveBy = tspSol.solveBy;
userTime = tspSol.userTime;
cpuTime = tspSol.cpuTime;
iterations = tspSol.iterations;
}
void initRandom(int seed = 42) {
srand(seed/*time(NULL)*/);
for (uint i = 1 ; i < sequence.size() ; ++i ) {
// initial and final position are fixed (initial/final node remains 0)
int idx1 = rand() % (sequence.size()-2) + 1;
int idx2 = rand() % (sequence.size()-2) + 1;
int tmp = sequence[idx1];
sequence[idx1] = sequence[idx2];
sequence[idx2] = tmp;
}
std::cout << "###" << std::endl;
print(std::cout);
std::cout << "###" << std::endl;
}
double evaluateObjectiveFunction(const TSP& tsp ) const {
double total = 0.0;
for ( uint i = 0 ; i < sequence.size() - 1 ; ++i ) {
int from = sequence[i] ;
int to = sequence[i+1];
total += tsp.cost[from][to];
}
return total;
}
void print(std::ostream& out) const {
out << std::endl;
for (uint i = 0; i < sequence.size(); i++ ) {
out << sequence[i] << " ";
}
out << std::endl;
}
TSPSolution& operator=(const TSPSolution& right) {
// Handle self-assignment:
if(this == &right) {
return *this;
}
else { // if (this != &right)
for (uint i = 0; i < sequence.size(); i++ ) {
sequence[i] = right.sequence[i];
}
}
return *this;
}
};
#endif /* TSPSOLUTION_H */