-
Notifications
You must be signed in to change notification settings - Fork 0
/
two-opt.js
53 lines (53 loc) · 1.16 KB
/
two-opt.js
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
module.exports = {
swap(s, i, j){
while(i < j){
let temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
return s;
},
run(s,distance_matrix){
let improve = true;
let local_gain;
let best_gain = -1;
let new_distance;
let first, second;
let total_gain = 0;
while(improve){
improve = false;
for(let i = 0; i < s.length; i++){
best_gain = 0;
for(let j = i + 2; j < s.length; j++){
let a = s[i]-1;
let b = s[i+1]-1;
let c = s[j]-1;
let d = s[(j+1) % s.length]-1;
if(!(distance_matrix[a][b] > distance_matrix[b][c]) && !(distance_matrix[c][d] > distance_matrix[c][a])) continue;
if(b == c || d == a) continue;
local_gain =
- distance_matrix[a][b]
- distance_matrix[c][d]
+ distance_matrix[a][c]
+ distance_matrix[b][d];
if (local_gain < best_gain) {
best_gain = local_gain;
first = i + 1;
second = j;
improve = true;
}
}
if(best_gain < 0){
total_gain += best_gain;
s = this.swap(s, first, second);
}
}
}
return {
solution: s,
gain: total_gain
};
}
}