twoOpt.cpp
Go to the documentation of this file.
1 //==================================================================
2 // File : twoOpt.cpp
3 // Author : rsagalyn
4 // Date : Aug 25, 2013
5 // Description :
6 //==================================================================
7 
8 #include "twoOpt.h"
9 
10 // Input: edge 1's v, edge 2's u
11 // Remove edge 1 and edge 2, reconnect using new path
12 void reverse(vector<int> &path, int start, int end, int n)
13 {
14  while (end - start > 0)
15  {
16  // Start, end is relative value to the start,
17  // the index is start|slut % size
18  int temp = path[start % n];
19  path[start % n] = path[end % n];
20  path[end % n] = temp;
21  start++;
22  end--;
23  }
24 }
25 
26 
27 int is_path_shorter(double **graph, int v1, int v2, int v3, int v4, double &total_dist)
28 {
29  if ((graph[v1][v3] + graph[v2][v4]) < (graph[v1][v2] + graph[v3][v4]))
30  {
31  total_dist -= (graph[v1][v2] + graph[v3][v4] - graph[v1][v3]
32  - graph[v2][v4]);
33  return 1;
34  }
35  return 0;
36 }
37 
38 
39 // Non-looping version of two-opt heuristic
40 double twoOpt(double **graph, vector<int> &path, double &pathLength, int n)
41 {
42  int counter = 0;
43  int term_cond = 5;
44  double old_distance = pathLength;
45  //int size = path.size();
46  int v1, v2, u1, u2;
47 
48  // Iterate over each edge
49  for (int i = 0; i < n; i++)
50  {
51  // first edge
52  u1 = i;
53  v1 = (i+1) % n; // wrap around to first node if u1 is last node
54 
55  // Skip adjacent edges, start with node one past v1
56  for (int j = i + 2; (j + 1) % n != i; j++)
57  {
58  // mod by length to go back to beginning
59  u2 = j % n;
60  v2 = (j+1) % n;
61 
62  // Check if new edges would shorten the path length
63  // If so, decreases pathLength
64  if (is_path_shorter(graph, path[u1], path[v1], path[u2],
65  path[v2], pathLength))
66  {
67 
68  // Swap u1--v1 and u2--v2
69  reverse(path, i + 1, j, n); // v1, u2
70 
71  if (pathLength - old_distance < 5 && counter == term_cond)
72  break;
73 
74  // reset i
75  if (pathLength - old_distance > term_cond )
76  i = 0;
77 
78  old_distance = pathLength;
79  counter++;
80  }
81  }
82  }
83  return pathLength;
84 }
85 
86 
87 
88 double get_path_length(double **graph, vector<int> &path, int size){
89  double length = 0;
90  for (int i = 0; i < size-1; i++)
91  {
92  length += graph[path[i]][path[i+1]];
93  }
94  length += graph[path[size-1]] [path[0]]; // back home
95  return length;
96 }
97 
98 
double twoOpt(double **graph, vector< int > &path, double &pathLength, int n)
Definition: twoOpt.cpp:40
double get_path_length(double **graph, vector< int > &path, int size)
Definition: twoOpt.cpp:88
int is_path_shorter(double **graph, int v1, int v2, int v3, int v4, double &total_dist)
Definition: twoOpt.cpp:27
void reverse(vector< int > &path, int start, int end, int n)
Definition: twoOpt.cpp:12


co_scan
Author(s):
autogenerated on Mon Feb 28 2022 23:00:56