Optimization with 2-OPT - Part 2 - Animated TSP Solver

## Algorithm

The algorithm implementation follows the 3 main steps described for Simulated Annealing in the previous post using stochastic sampling, but now applied to TSP:

1. Find a trial Solution $$s \in S$$, for which M(s) is as small as we can make it at a first try.
2. Apply some transformations, called ‘inversions’, which transforms this trial solutions into some other elements of S, whose measures are progressive smaller.
3. Check C for elements which might be included in the final s at an advantage. If there are any such elements try to find a transformation which decreases the measure of the sequence.

The JavaScript code follows (and for any other language really, the implementation is trivial):

That’s pretty much the algorithm behind the interactive demo at the beginning of this page. It is executed until the given ‘iteration limit’ is reached or until there’s no cost improvement after reversing the edges, whatever comes first.