Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 827785
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T03:37:32+00:00 2026-05-15T03:37:32+00:00

Can someone give me a code sample of 2-opt algorithm for traveling salesman problem.

  • 0

Can someone give me a code sample of 2-opt algorithm for traveling salesman problem. For now im using nearest neighbour to find the path but this method is far from perfect, and after some research i found 2-opt algorithm that would correct that path to the acceptable level. I found some sample apps but without source code.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T03:37:32+00:00Added an answer on May 15, 2026 at 3:37 am

    So I got bored and wrote it. It looks like it works, but I haven’t tested it very thoroughly. It assumes triangle inequality, all edges exist, that sort of thing. It works largely like the answer I outlined. It prints each iteration; the last one is the 2-optimized one.

    I’m sure it can be improved in a zillion ways.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    
    namespace TSP
    {
        internal static class Program
        {
            private static void Main(string[] args)
            {
                //create an initial tour out of nearest neighbors
                var stops = Enumerable.Range(1, 10)
                                      .Select(i => new Stop(new City(i)))
                                      .NearestNeighbors()
                                      .ToList();
    
                //create next pointers between them
                stops.Connect(true);
    
                //wrap in a tour object
                Tour startingTour = new Tour(stops);
    
                //the actual algorithm
                while (true)
                {
                    Console.WriteLine(startingTour);
                    var newTour = startingTour.GenerateMutations()
                                              .MinBy(tour => tour.Cost());
                    if (newTour.Cost() < startingTour.Cost()) startingTour = newTour;
                    else break;
                }
    
                Console.ReadLine();
            }
    
    
            private class City
            {
                private static Random rand = new Random();
    
    
                public City(int cityName)
                {
                    X = rand.NextDouble() * 100;
                    Y = rand.NextDouble() * 100;
                    CityName = cityName;
                }
    
    
                public double X { get; private set; }
    
                public double Y { get; private set; }
    
                public int CityName { get; private set; }
            }
    
    
            private class Stop
            {
                public Stop(City city)
                {
                    City = city;
                }
    
    
                public Stop Next { get; set; }
    
                public City City { get; set; }
    
    
                public Stop Clone()
                {
                    return new Stop(City);
                }
    
    
                public static double Distance(Stop first, Stop other)
                {
                    return Math.Sqrt(
                        Math.Pow(first.City.X - other.City.X, 2) +
                        Math.Pow(first.City.Y - other.City.Y, 2));
                }
    
    
                //list of nodes, including this one, that we can get to
                public IEnumerable<Stop> CanGetTo()
                {
                    var current = this;
                    while (true)
                    {
                        yield return current;
                        current = current.Next;
                        if (current == this) break;
                    }
                }
    
    
                public override bool Equals(object obj)
                {
                    return City == ((Stop)obj).City;
                }
    
    
                public override int GetHashCode()
                {
                    return City.GetHashCode();
                }
    
    
                public override string ToString()
                {
                    return City.CityName.ToString();
                }
            }
    
    
            private class Tour
            {
                public Tour(IEnumerable<Stop> stops)
                {
                    Anchor = stops.First();
                }
    
    
                //the set of tours we can make with 2-opt out of this one
                public IEnumerable<Tour> GenerateMutations()
                {
                    for (Stop stop = Anchor; stop.Next != Anchor; stop = stop.Next)
                    {
                        //skip the next one, since you can't swap with that
                        Stop current = stop.Next.Next;
                        while (current != Anchor)
                        {
                            yield return CloneWithSwap(stop.City, current.City);
                            current = current.Next;
                        }
                    }
                }
    
    
                public Stop Anchor { get; set; }
    
    
                public Tour CloneWithSwap(City firstCity, City secondCity)
                {
                    Stop firstFrom = null, secondFrom = null;
                    var stops = UnconnectedClones();
                    stops.Connect(true);
    
                    foreach (Stop stop in stops)
                    {
                        if (stop.City == firstCity) firstFrom = stop;
    
                        if (stop.City == secondCity) secondFrom = stop;
                    }
    
                    //the swap part
                    var firstTo = firstFrom.Next;
                    var secondTo = secondFrom.Next;
    
                    //reverse all of the links between the swaps
                    firstTo.CanGetTo()
                           .TakeWhile(stop => stop != secondTo)
                           .Reverse()
                           .Connect(false);
    
                    firstTo.Next = secondTo;
                    firstFrom.Next = secondFrom;
    
                    var tour = new Tour(stops);
                    return tour;
                }
    
    
                public IList<Stop> UnconnectedClones()
                {
                    return Cycle().Select(stop => stop.Clone()).ToList();
                }
    
    
                public double Cost()
                {
                    return Cycle().Aggregate(
                        0.0,
                        (sum, stop) =>
                        sum + Stop.Distance(stop, stop.Next));
                }
    
    
                private IEnumerable<Stop> Cycle()
                {
                    return Anchor.CanGetTo();
                }
    
    
                public override string ToString()
                {
                    string path = String.Join(
                        "->",
                        Cycle().Select(stop => stop.ToString()).ToArray());
                    return String.Format("Cost: {0}, Path:{1}", Cost(), path);
                }
    
            }
    
    
            //take an ordered list of nodes and set their next properties
            private static void Connect(this IEnumerable<Stop> stops, bool loop)
            {
                Stop prev = null, first = null;
                foreach (var stop in stops)
                {
                    if (first == null) first = stop;
                    if (prev != null) prev.Next = stop;
                    prev = stop;
                }
    
                if (loop)
                {
                    prev.Next = first;
                }
            }
    
    
            //T with the smallest func(T)
            private static T MinBy<T, TComparable>(
                this IEnumerable<T> xs,
                Func<T, TComparable> func)
                where TComparable : IComparable<TComparable>
            {
                return xs.DefaultIfEmpty().Aggregate(
                    (maxSoFar, elem) =>
                    func(elem).CompareTo(func(maxSoFar)) > 0 ? maxSoFar : elem);
            }
    
    
            //return an ordered nearest neighbor set
            private static IEnumerable<Stop> NearestNeighbors(this IEnumerable<Stop> stops)
            {
                var stopsLeft = stops.ToList();
                for (var stop = stopsLeft.First();
                     stop != null;
                     stop = stopsLeft.MinBy(s => Stop.Distance(stop, s)))
                {
                    stopsLeft.Remove(stop);
                    yield return stop;
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can someone give me a sample code to confine the cursor on to a
Can someone give me an sample code for changing volume through a slider? I
I hope someone can give me your help ... (Any sample code would be
Can someone give me some code to set the cell of an excel spreadsheet
can someone give me a hint on how a histogram's pseudo code would look
Can someone give an example for finding greatest common divisor algorithm for more than
Can someone find a strategy for this problem that DOESN'T INVOLVE CONVERTING TO BASE
I have a problem, hopefully someone can give me some hints. Environment: maven project
Can someone give me some advice on this? I am reading in an old
Can someone give me a Powershell script that will change the format of all

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.