tsp

A Traveling Salesman Problem solver for the command line, written in C# 14 on .NET 10 and shipped as a single Native AOT binary.

The problem

Given a set of cities and the distance between every pair, the Traveling Salesman Problem asks for the shortest round trip that visits each city exactly once and returns to the start. It is NP-hard: the number of distinct tours of n cities is (n − 1)!/2, so exact search stops being practical after a few dozen cities. Logistics, circuit board drilling, genome assembly and telescope scheduling all reduce to it, which is why fast heuristics matter.

Algorithms

KeyAlgorithmCostIdea
nearest-neighborNearest NeighborO(n²)Always travel to the closest unvisited city. Fast and deterministic, typically 20–25% above optimal.
two-opt2-OptO(n²) per passStart from Nearest Neighbor and reverse any segment that shortens the route, until no such move remains. Removes every crossing.
simulated-annealingSimulated AnnealingO(steps × iterations)Random 2-opt moves that sometimes accept a longer route, with a probability that falls as the temperature cools, to escape local optima.
geneticGenetic AlgorithmO(generations × population × n)Evolve a population of routes with tournament selection, order crossover, inversion mutation and elitism, stopping early when progress stalls.

The three improving algorithms are seeded with the Nearest Neighbor tour, so they never return anything longer than it.

Try it

curl -fsSL https://raw.githubusercontent.com/kusl/tsp/master/scripts/install.sh | sudo bash
kusl-tsp solve --cities 30 --algorithm genetic --seed 7 --plot
kusl-tsp benchmark --cities 50 --pattern circle

Or with Podman:

podman build --file Containerfile --tag localhost/tsp .
podman run --rm localhost/tsp benchmark --cities 40 --seed 42

Build from source

git clone https://github.com/kusl/tsp.git
cd tsp
time bash scripts/ci.sh

The pipeline lints the scripts, builds the solution, runs the xUnit v3 and Reqnroll tests on Microsoft Testing Platform, smoke tests the CLI, publishes a Native AOT binary, builds the container image and exports the source to docs/llm/dump.txt.