Travel Salesman Problem
Travel Salesman Problem
Travel Salesman Problem
h>
#include <GL/glut.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
//
// To display onto window using OpenGL commands
//
void display()
{
//
// clear window to black
//
glClearColor( 0, 0 , 0 , 0 );
glClear( GL_COLOR_BUFFER_BIT );
glLoadIdentity();
//orange color
glColor3ub(200, 100, 15);
//draw path
glBegin(GL_LINE_LOOP);
for (int k = 0; k < nCities; k++)
glVertex2i(arrayCities[position[k]].x, arrayCities[position[k]].y);
glEnd();
//return the total distance from initial city to the last one + last one to the
initial one
double computeDistance()
{
double distancePath = 0.0;
for (int k = 0; k < nCities - 1; k++)
distancePath += distances[position[k]][position[k + 1]];
distancePath += distances[position[nCities - 1]][position[0]];
return distancePath;
}
//
// key function for ASCII charachters like ESC, a,b,c..,A,B,..Z
//
void onKeyDown(unsigned char key, int x, int y )
{
// exit when ESC is pressed.
if (key == 27)
exit(0);
else if (key == 'a')
{
getShortestPath();
printf("Initial distance: %lf; Shortest path: %lf\n", initialDistance,
computeDistance());
}
else if (key == 's')
{
int e1, e2;
double d1 = computeDistance();
Swap2Elements(&e1, &e2);
double d2 = computeDistance();
if (d2 > d1)
{
//revert the swaps
int temp = position[e1];
position[e1] = position[e2];
position[e2] = temp;
}
printf("Distance: %lf \n", computeDistance());
}
// to refresh the window it calls display() function
glutPostRedisplay() ;
}
//
// This function is called when the window size changes.
// w : is the new width of the window in pixels.
// h : is the new height of the window in pixels.
//
void onResize( int w, int h )
{
glViewport( 0,0,w,h) ;
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( -w/2, w/2, -h/2, h/2, -1, 1);
glMatrixMode( GL_MODELVIEW);
glLoadIdentity();
}
initialDistance = computeDistance();
printf("Initial distance: %lf\n", initialDistance);
}
glutDisplayFunc( display ) ;
glutIdleFunc(display);
glutReshapeFunc( onResize );
//
// keyboard registration
//
glutKeyboardFunc( onKeyDown ) ;
Init(n);
glutMainLoop();
return 0;
}