} } printf("\n];\n"); } // Create a path of length n with random points betweeen 0 and 1000 vector<Point> createRandomPath(int n) { vector<Point> path; for (int i = 0; i < n; i++) { path.push_back(Point(rand() % 1000, rand() % 1000)); } return path; } int main() { vector<Point> path = createRandomPath(100); printPath("path1", path); int curLength = pathLengthSq(path); int n = path.size(); bool foundImprovement = true; while (foundImprovement) { foundImprovement = false; for (int i = 0; i <= n - 2; i++) { for (int j = i + 1; j <= n - 1; j++) { int lengthDelta = -path[i].dist2(path[(i + 1) % n]) - path[j].dist2(path[(j + 1) % n]) + path[i].dist2(path[j]) + path[(i + 1) % n].dist2(path[(j + 1) % n]); // If the length of the path is reduced, do a 2-opt swap if (lengthDelta < 0) { do2Opt(path, i, j); curLength += lengthDelta; foundImprovement = true; } } } } printPath("path2", path); return 0; } Output path1 = [ [ 743, 933], [ 529, 262], [ 508, 700], [ 256, 752], [ 119, 256], [ 351, 711], [ 705, 843], [ 393, 108], [ 366, 330], [ 932, 169], [ 847, 917], [ 868, 972], [ 223, 980], [ 592, 549], [ 169, 164], [ 427, 551], [ 624, 190], [ 920, 635], [ 310, 944], [ 484, 862], [ 301, 363], [ 236, 710], [ 431, 876], [ 397, 929], [ 491, 675], [ 344, 190], [ 425, 134], [ 30, 629], [ 126, 727], [ 334, 743], [ 760, 104], [ 620, 749], [ 932, 256], [ 613, 572], [ 509, 490], [ 405, 119], [ 49, 695], [ 719, 327], [ 824, 497], [ 649, 596], [ 184, 356], [ 245, 93], [ 306, 7], [ 754, 509], [ 665, 352], [ 738, 783], [ 690, 801], [ 337, 330], [ 656, 195], [ 11, 963], [ 42, 427], [ 968, 106], [ 1, 212], [ 480, 510], [ 571, 658], [ 814, 331], [ 564, 847], [ 625, 197], [ 931, 438], [ 487, 18], [ 187, 151], [ 179, 913], [ 750, 995], [ 913, 750], [ 134, 562], [ 547, 273], [ 830, 521], [ 557, 140], [ 726, 678], [ 597, 503], [ 893, 408], [ 238, 988], [ 93, 85], [ 720, 188], [ 746, 211], [ 710, 387], [ 887, 209], [ 103, 668], [ 900, 473],