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
|
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
double routes;
double current_length;
double min=10000;
//State coordinates of each house and saves them into 2 1x15 arrays
double x_coords[15] = {4, 18, 2, 48, 88, 36, 57, 83, 64, 77, 35, 84, 3, 95, 3};
double y_coords[15] = {58, 1, 25, 96, 22, 50, 12, 97, 4, 53, 63, 12, 42, 88, 45};
//ask the user for the desired number of routes to test
cout << "How many routes would you like to test? ";
cin >> routes;
//Set seed based on clock
int order[15]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14};
srand (time(NULL));
//generate a random route and calculate distance, repeat until "routes" has been met
for ( int i = 0 ; i < routes ; i= i + 1)
{
random_shuffle(&order[0],&order[15]);
//calculate distance of route using pathagorean theorem
current_length = sqrt(pow(x_coords[order[1]] - x_coords[order[0]],2)+pow(y_coords[order[1]] - y_coords[order[0]],2))+
sqrt(pow(x_coords[order[2]] - x_coords[order[1]],2)+pow(y_coords[order[2]] - y_coords[order[1]],2))+
sqrt(pow(x_coords[order[3]] - x_coords[order[2]],2)+pow(y_coords[order[3]] - y_coords[order[2]],2))+
sqrt(pow(x_coords[order[4]] - x_coords[order[3]],2)+pow(y_coords[order[4]] - y_coords[order[3]],2))+
sqrt(pow(x_coords[order[5]] - x_coords[order[4]],2)+pow(y_coords[order[5]] - y_coords[order[4]],2))+
sqrt(pow(x_coords[order[6]] - x_coords[order[5]],2)+pow(y_coords[order[6]] - y_coords[order[5]],2))+
sqrt(pow(x_coords[order[7]] - x_coords[order[6]],2)+pow(y_coords[order[7]] - y_coords[order[6]],2))+
sqrt(pow(x_coords[order[8]] - x_coords[order[7]],2)+pow(y_coords[order[8]] - y_coords[order[7]],2))+
sqrt(pow(x_coords[order[9]] - x_coords[order[8]],2)+pow(y_coords[order[9]] - y_coords[order[8]],2))+
sqrt(pow(x_coords[order[10]] - x_coords[order[9]],2)+pow(y_coords[order[10]] - y_coords[order[9]],2))+
sqrt(pow(x_coords[order[11]] - x_coords[order[10]],2)+pow(y_coords[order[11]] - y_coords[order[10]],2))+
sqrt(pow(x_coords[order[12]] - x_coords[order[11]],2)+pow(y_coords[order[12]] - y_coords[order[11]],2))+
sqrt(pow(x_coords[order[13]] - x_coords[order[12]],2)+pow(y_coords[order[13]] - y_coords[order[12]],2))+
sqrt(pow(x_coords[order[14]] - x_coords[order[13]],2)+pow(y_coords[order[14]] - y_coords[order[13]],2));
min = (current_length < min)? current_length:min; // test whether new route is shorter than previous minimum
}
cout << "The shortest route tested is " << min << " miles. " <<endl << "The coordinates are: " << endl;
for (int i = 0; i < 15; i = i+1)
{
cout << "(" << x_coords[order[i]] << "," << y_coords[order[i]] << ")" << endl; //outputs the (x,y) coordinates in the randomized order generated
// cout << (order[i]) << " " << endl; //checks if order of route and coordinates match.
}
return 0;
}
|