Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio .NET » How to use Genetic Algorithm for Traveling Salesman Problem

How to use Genetic Algorithm for Traveling Salesman Problem

TSP is a famous math problem: Given a number of cities and the costs of traveling from any city to any other city, what is the cheapest round-trip route that visits each city exactly once and then returns to the starting city? We use the Genetic Algorithm to solve the TSP problem as a C# programing example .

Total page views :  25337
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

The Travelling Salesman Problem (TSP) problem is programmed by using C#.NET.

Please feel free to re-use the source codes.

A genetic algorithm is a adaptive stochastic optimization algorithms involving search and optimization. The evolutionary algorithm applies the principles of evolution found in nature to the problem of finding an optimal solution to a Solver problem. 

The traveling salesman problem (TSP) is a problem in discrete or combinatorial optimisation. It is a prominent illustration of a class of problems in computational complexity theory which are hard to solve.

An equivalent formulation in terms of graph theory is: Given a complete weighted graph (where the vertices would represent the cities, the edges would represent the roads, and the weights would be the cost or distance of that road), find a Hamiltonian cycle with the least weight.

It can be shown that the requirement of returning to the starting city does not change the computational complexity of the problem.

A related problem is the bottleneck traveling salesman problem: Find a Hamiltonian cycle in a weighted graph with the minimal length of the longest edge. 

---------------------------- Below are the source codes ----------------------------------

///////////////////////////// Travelling Salesman Problem (TSP) ///////////////////////////////

 

// TSP is a famous math problem: Given a number of cities and the costs of traveling

 

// from any city to any other city, what is the cheapest round-trip route that visits

 

// each city exactly once and then returns to the starting city?

 

///////////////////////////////////////////////////////////////////////////////////////////////

 

///---------------------- Begin CHROMOSOME.CS ----------------------------------------

 

using System;

using System.Threading;

namespace simga

{

          /// <summary>

          /// Summary description for Chromosome.

          /// </summary>

          public class Chromosome

          {

                   public Chromosome()

                   {

                             //

                             // TODO: Add constructor logic here

                             //

                   }

 

                   // The cost for the fitness of the chromosome

                   protected double cost;

                   Random randObj = new Random();

                   //City myCity = new City();

                   // The list of cities which are the genes of the chromosome

                   protected int [] cityList;

                   // The mutation rate at percentage.

                   protected double mutationPercent;

                   // crossover point.

                   protected int crossoverPoint;

 

                   public Chromosome( City [] cities)

                    {

                             bool [] taken = new bool[cities.Length];

                             cityList = new int[cities.Length];

                             cost = 0.0;

                             for ( int i=0; i<cityList.Length; i++ ) taken[i] = false;

                             for ( int i=0; i<cityList.Length-1; i++ )

                             {

                                      int icandidate;

                                      do

                                      {

                                                icandidate = (int) ( randObj.NextDouble() * (double) cityList.Length );

                                      } while ( taken[icandidate] );

                                      cityList[i] = icandidate;

                                      taken[icandidate] = true;

                                      if ( i == cityList.Length-2 )

                                      {

                                                icandidate = 0;

                                                while ( taken[icandidate] ) icandidate++;

                                                cityList[i+1] = icandidate;

                                      }

                             }

                             calculateCost(cities);

                             crossoverPoint = 1;

                   }

 

                   // fitness calculation

                   //void calculateCost(myCity cities)

                   public void calculateCost(City [] cities)

                   {

                             cost=0;

                             for ( int i=0; i<cityList.Length-1; i++ )

                             {

                                      double dist = cities[cityList[i]].proximity(cities[cityList[i+1]]);

                                      cost += dist;

                             }

                   }

 

                   public double getCost()

                   {

                             return cost;

                   }

 

                   public int getCity(int i)

                   {

                             return cityList[i];

                   }

 

                   public void assignCities(int [] list)

                   {

                             for ( int i=0; i<cityList.Length; i++ )

                             {

                                      cityList[i] = list[i];

                             }

                   }

 

                   public void assignCity(int index, int value)

                   {

                             cityList[index] = value;

                   }

 

                   public void assignCut(int cut)

                   {

                             crossoverPoint = cut;

                   }

 

                   public void assignMutation(double prob)

                   {

                             mutationPercent = prob;

                   }

 

                   public int mate(Chromosome father, Chromosome offspring1, Chromosome offspring2)

                   {

                             int crossoverPostion1 = (int) ((randObj.NextDouble())*(double)(cityList.Length-crossoverPoint));

                             int crossoverPostion2 = crossoverPostion1 + crossoverPoint;

                             int [] offset1 = new int[cityList.Length];

                             int [] offset2 = new int[cityList.Length];

                             bool [] taken1 = new bool[cityList.Length];

                             bool [] taken2 = new bool[cityList.Length];

                             for ( int i=0; i<cityList.Length; i++ )

                             {

                                      taken1[i] = false;

                                      taken2[i] = false;

                             }

                             for ( int i=0; i<cityList.Length; i++ )

                             {

                                      if ( i<crossoverPostion1 || i>= crossoverPostion2 )

                                      {

                                                offset1[i] = -1;

                                                offset2[i] = -1;

                                      }

                                      else

                                      {

                                                int imother = cityList[i];

                                                int ifather = father.getCity(i);

                                                offset1[i] = ifather;

                                                offset2[i] = imother;

                                                taken1[ifather] = true;

                                                taken2[imother] = true;

                                      }

                             }

                             for ( int i=0; i<crossoverPostion1; i++ )

                             {

                                      if ( offset1[i] == -1 )

                                      {

                                                for ( int j=0;j<cityList.Length;j++ )

                                                {

                                                          int imother = cityList[j];

                                                          if ( !taken1[imother] )

                                                          {

                                                                   offset1[i] = imother;

                                                                   taken1[imother] = true;

                                                                   break;

                                                          }

                                                }

                                      }

                                      if ( offset2[i] == -1 )

                                      {

                                                for ( int j=0;j<cityList.Length;j++ )

                                                {

                                                          int ifather = father.getCity(j);

                                                          if ( !taken2[ifather] )

                                                          {

                                                                   offset2[i] = ifather;

                                                                   taken2[ifather] = true;

                                                                   break;

                                                          }

                                                }

                                      }

                             }

                             for ( int i=cityList.Length-1; i>=crossoverPostion2; i-- )

                             {

                                      if ( offset1[i] == -1 )

                                      {

                                                for ( int j=cityList.Length-1;j>=0;j-- )

                                                {

                                                          int imother = cityList[j];

                                                          if ( !taken1[imother] )

                                                          {

                                                                   offset1[i] = imother;

                                                                   taken1[imother] = true;

                                                                   break;

                                                          }

                                                }

                                      }

                                      if ( offset2[i] == -1 )

                                      {

                                                for ( int j=cityList.Length-1;j>=0;j-- )

                                                {

                                                          int ifather = father.getCity(j);

                                                          if ( !taken2[ifather] )

                                                          {

                                                                   offset2[i] = ifather;

                                                                   taken2[ifather] = true;

                                                                   break;

                                                          }

                                                }

                                      }

                             }

                             offspring1.assignCities(offset1);

                             offspring2.assignCities(offset2);

                             int mutate = 0;

                             int swapPoint1 = 0;

                             int swapPoint2 = 0;

                             if ( randObj.NextDouble() < mutationPercent )

                             {

                                      swapPoint1 = (int) (randObj.NextDouble()*(double)(cityList.Length));

                                      swapPoint2 = (int) (randObj.NextDouble()*(double)cityList.Length);

                                      int i = offset1[swapPoint1];

                                      offset1[swapPoint1] = offset1[swapPoint2];

                                      offset1[swapPoint2] = i;

                                      mutate++;

                             }

                             if ( randObj.NextDouble() < mutationPercent )

                             {

                                      swapPoint1 = (int) (randObj.NextDouble()*(double)(cityList.Length));

                                      swapPoint2 = (int) (randObj.NextDouble()*(double)cityList.Length);

                                      int i = offset2[swapPoint1];

                                      offset2[swapPoint1] = offset2[swapPoint2];

                                      offset2[swapPoint2] = i;

                                      mutate++;

                             }

                             return mutate;

                   }

                   public void PrintCity(int i, City [] cities)

                  {

                          System.Console.WriteLine("City "+i.ToString()+": ("+cities[cityList[i]].getx().ToString()+", "

                            + cities[cityList[i]].gety().ToString()+")");

                  }

 

                   // chromosomes -- an array of chromosomes which is sorted

                   // num -- the number of the chromosome list

                   public static void sortChromosomes(Chromosome [] chromosomes,int num)

                   {

                             bool swapped = true;

                             Chromosome dummy;

                             while ( swapped )

                             {

                                      swapped = false;

                                      for ( int i=0; i<num-1; i++ )

                                      {

                                                if ( chromosomes[i].getCost() > chromosomes[i+1].getCost() )

                                                {

                                                          dummy = chromosomes[i];

                                                          chromosomes[i] = chromosomes[i+1];

                                                          chromosomes[i+1] = dummy;

                                                          swapped = true;

                                                }

                                      }

                             }

                   }

          }

}

//// ---------------------------- end CHROMOSOME.CS -------------------------------

 

 

/// ---------------------------- begin GA_TSP.CS --------------------------------------

using System;

using System.Threading;

using System.IO;

namespace simga

{

          /// <summary>

          /// Summary description for Class1.

          /// </summary>

          class GA_TSP

          {

                   protected int cityCount;

                   protected int populationSize;

                   protected double mutationPercent;

                   protected int matingPopulationSize;

                   protected int favoredPopulationSize;

                   protected int cutLength;

                   protected int generation;

                   protected Thread worker = null;

                   protected bool started = false;

                   protected City [] cities;

                   protected Chromosome [] chromosomes;

                   private string status = "";

                   public GA_TSP()

                   {

                   }

 

                   public void Initialization()

                   {

                             Random randObj = new Random();

                             try

                             {

                                      cityCount = 40;

                                      populationSize = 1000;

                                      mutationPercent = 0.05;

                             }

                             catch(Exception e)

                             {

                                      cityCount = 100;

                             }

                             matingPopulationSize = populationSize/2;

                             favoredPopulationSize = matingPopulationSize/2;

                             cutLength = cityCount/5;

                             // create a random list of cities

                             cities = new City[cityCount];

                             for ( int i=0;i<cityCount;i++ )

                             {

                                      cities[i] = new City(

                                                (int)(randObj.NextDouble()*30),(int)(randObj.NextDouble()*15));

                             }

 

                             // create the initial chromosomes

                             chromosomes = new Chromosome[populationSize];

                             for ( int i=0;i<populationSize;i++ )

                             {

                                      chromosomes[i] = new Chromosome(cities);

                                      chromosomes[i].assignCut(cutLength);

                                      chromosomes[i].assignMutation(mutationPercent);

                             }

                             Chromosome.sortChromosomes(chromosomes,populationSize);

                             started = true;

                             generation = 0;

                   }

 

                   public void TSPCompute()

                   {

                             double thisCost = 500.0;

                             double oldCost = 0.0;

                             double dcost = 500.0;

                             int countSame = 0;

                             Random randObj = new Random();

                             while(countSame<120)

                             {

                                      generation++;

                                      int ioffset = matingPopulationSize;

                                      int mutated = 0;

                                      for ( int i=0;i<favoredPopulationSize;i++ )

                                      {

                                                Chromosome cmother = chromosomes[i];

                                                int father = (int) ( randObj.NextDouble()*(double)matingPopulationSize);

                                                Chromosome cfather = chromosomes[father];

                                                mutated += cmother.mate(cfather,chromosomes[ioffset],chromosomes[ioffset+1]);

                                                ioffset += 2;

                                      }

                                      for ( int i=0;i<matingPopulationSize;i++ )

                                      {

                                                chromosomes[i] = chromosomes[i+matingPopulationSize];

                                                chromosomes[i].calculateCost(cities);

                                      }

                                      // Now sort the new population

                                      Chromosome.sortChromosomes(chromosomes,matingPopulationSize);

                                      double cost = chromosomes[0].getCost();

                                      dcost = Math.Abs(cost-thisCost);

                                      thisCost = cost;

                                      double mutationRate = 100.0 * (double) mutated / (double) matingPopulationSize;

                                      System.Console.WriteLine("Generation = "+generation.ToString()+" Cost = "+thisCost.ToString()+" Mutated Rate = "+mutationRate.ToString()+"%");

                                      if ( (int)thisCost == (int)oldCost )

                                      {

                                                countSame++;

                                      }

                                      else

                                      {

                                                countSame = 0;

                                                oldCost = thisCost;

                                                //System.Console.WriteLine("oldCost = " + oldCost.ToString());

                                      }

                             }

                             for(int i = 0; i < cities.Length; i++)

                             {

                                  chromosomes[i].PrintCity(i, cities);

                        }

                   }

 

                   /// <summary>

                   /// The main entry point for the application.

                   /// </summary>

                   [STAThread]

                   static void Main(string[] args)

                   {

                             //

                             // TODO: Add code to start application here

                             //

                             GA_TSP tsp = new GA_TSP();

                             tsp.Initialization();

                             tsp.TSPCompute();

                   }

          }

 

          public class City

          {

                   public City()

                   {

                             //

                             // TODO: Add constructor logic here

                             //

                   }

                   // The city's x coordinate.

                   private int xcoord;

                   // The city's y coordinate.

                   private int ycoord;

                   // x -- the city's x coordinate

                   // y -- the city's y coordinate

                   public City(int x, int y)

                   {

                             xcoord = x;

                             ycoord = y;

                   }

 

                   public int getx()

                   {

                             return xcoord;

                   }

 

                   public int gety()

                   {

                             return ycoord;

                   }

 

                   // Returns the distance from the city to another city.

                   public int proximity(City cother)

                   {

                             return proximity(cother.getx(),cother.gety());

                   }

 

                   // x -- the x coordinate

                   // y -- the y coordinate

                   // return The distance.

                   public int proximity(int x, int y)

                   {

                             int xdiff = xcoord - x;

                             int ydiff = ycoord - y;

                             return(int)Math.Sqrt( xdiff*xdiff + ydiff*ydiff );

                   }

          }

}

////----------------------- end GA_TSP.CS ------------------------------------------------------ 

Below is the optimal solution for the GA algorithm. In order to re-use the source codes easily, we removed the GUI program in the example above.  If you compile and run the program, the optimal solution will appear in the DOS window as follow.

 

If we show the optimal solution in graph (that is, we connect the cities in the order), the graph will look like below:

 


Login to add your contents and source code to this article
 About the author
 
Yuan Wang
Yuan is working in an IT firm of Northern VA. He has over 10 years experience in mathematical modeling, parallel computing, and programming. He is currently working with Java, C++ and .NET mostly for modeling, simulation, and web application development with SQL Server and Oracle. In his past life, Yuan's Ph.D research was focused on Applied Probabilistic Models, Operations Research and Parellel Computing.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
genetic algorithms in C# by farayi On February 20, 2007
hi i was impressed by your interest in GA for the TSP. Do you by any chance have or know any GA for TSP in C++? i am working on a project and i need a starting point like the one that you presented in C# thanks
Reply | Email | Delete | Modify | 
No return leg changes the path. by Don On July 14, 2009
The connection between the 1st and last cities is not represented in the path or on the graph. A quick eye-ball of the graph seems to yield that this is not the shortest path if the return trip is considered and that there are alternate routes that would be better WHEN considering the return trip.
Reply | Email | Delete | Modify | 
genetic algorithms for school timetabling by kshito On August 13, 2009
I there, Do you have an idea of how to solve timetabling using a GA; Im a newbie in GA's.
Thanks in advance
Reply | Email | Delete | Modify | 
Excellent by Mus On December 15, 2009
Excellent a study
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.