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
|
// TSP_BruteForce.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
float distance(float x1, float x2, float y1, float y2);
int _tmain(int argc, _TCHAR* argv[])
{
int NumberOfPoints;
srand (7);
cout << "Please enter the number of points: " << endl;
cin >> NumberOfPoints;
cout << endl;
vector <float> x(NumberOfPoints);
vector <float> y(NumberOfPoints);
vector <int> order(NumberOfPoints);
float TotalDistance = 0;
float ShortestDistance = 9999; // set this to a high target initially
//vector< vector<float> > DistanceArray(NumberOfPoints, vector<float>(NumberOfPoints));
// ***********************************************************************************************************
// this bit is getting a set of random numbers
for (int i = 0; i < NumberOfPoints; i++){ // this loop calculates 2 sets of random numbers (x,y) and sets order to be 0,1,2,3....
x[i] = 10 * rand() / float(RAND_MAX);
y[i] = 10 * rand() / float(RAND_MAX);
order[i] = i;
std::cout << i << " " << x[i] << " " << y[i] << std::endl;
}
// ***********************************************************************************************************
// we have n sets of x,y values - set up a loop to calculate the total distance travelled, and permute
do {
TotalDistance = 0;
for (int i = 0; i < NumberOfPoints - 1; i++){
TotalDistance += distance(x[order[i]], x[order[i+1]], y[order[i]], y[order[i+1]]);
}
if (TotalDistance < ShortestDistance){
ShortestDistance = TotalDistance;
cout << "Shortest Distance: " << ShortestDistance << endl;
for (int j = 0; j < NumberOfPoints; j++){
cout << order[j] << " ";
}
cout << endl;
}
} while (next_permutation(order.begin(), order.end() ));
std::cout << std::endl;
system("PAUSE");
return 0;
}
float distance(float x1, float x2, float y1, float y2){ // function to calculate the (Euclidian) distance between 2 sets of points.
return sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
}
|