tsp-solver-nn
Version:
A Typescript implementation of the Nearest Neighbor with 2-opt and 3-opt optimizations to solve the travelling salesman problem (TSP).
80 lines (60 loc) • 5.26 kB
Markdown
# tsp-solver-nn
A Typescript implementation of the [Nearest Neighbour algorithm](https://en.wikipedia.org/wiki/Nearest_neighbour_algorithm) with [2-opt](https://en.wikipedia.org/wiki/2-opt) and [3-opt](https://en.wikipedia.org/wiki/3-opt) optimizations for solving the [travelling salesman problem](https://en.wikipedia.org/wiki/Traveling_salesman_problem), for both [Hamiltonian paths and cycles](https://en.wikipedia.org/wiki/Hamiltonian_path). Supports both Javascript and Typescript.
```sh
npm install tsp-solver-nn
```
The Nearest Neighbour algorithm approximates TSP solutions with the advantage of being very quick, but can get stuck in local minima. This issue can be mitigated by applying 2-opt and/or 3-opt optimizations refinements to the tour by reconnecting edges to reduce crossings and shorten the route, yielding much better results than Nearest Neighbour alone.
Although exact algorithms for solving the TSP exist, they often demand much greater computational power and memory, making them impractical for large datasets or resource-constrained environments. This implementation offers a fast and reasonably accurate solution, making it well-suited for scenarios where a near-optimal result is sufficient and performance is a priority.
## API
### Example
```js
import { TSPSolverNN } from "../src/TSPSolverNN"
import assert from 'node:assert/strict'
// Symmetric case from https://stackoverflow.com/a/27195735
const cities = [
[0, 29, 20, 21, 16, 31, 100, 12, 4, 31, 18],
[29, 0, 15, 29, 28, 40, 72, 21, 29, 41, 12],
[20, 15, 0, 15, 14, 25, 81, 9, 23, 27, 13],
[21, 29, 15, 0, 4, 12, 92, 12, 25, 13, 25],
[16, 28, 14, 4, 0, 16, 94, 9, 20, 16, 22],
[31, 40, 25, 12, 16, 0, 95, 24, 36, 3, 37],
[100, 72, 81, 92, 94, 95, 0, 90, 101, 99, 84],
[12, 21, 9, 12, 9, 24, 90, 0, 15, 25, 13],
[4, 29, 23, 25, 20, 36, 101, 15, 0, 35, 18],
[31, 41, 27, 13, 16, 3, 99, 25, 35, 0, 38],
[18, 12, 13, 25, 22, 37, 84, 13, 18, 38, 0],
]
const tspSolver = new TSPSolverNN()
assert.deepEqual(tspSolver.getCycle(cities), {
distance: 253, route: [0, 8, 10, 1, 6, 2, 5, 9, 3, 4, 7, 0],
})//optimal: 253
assert.deepEqual(tspSolver.getPath(cities), {
distance: 170, route: [0, 8, 7, 4, 3, 9, 5, 2, 10, 1, 6],
})//optimal: 160
// degenerate case with 1 city
const degenerate = [
[0]
]
assert.deepEqual(tspSolver.getCycle(degenerate), { distance: 0, route: [0, 0] })
assert.deepEqual(tspSolver.getPath(degenerate), { distance: 0, route: [0] })
```
#### getCycle(distanceMatrix: number[][], optimizations?: {twoOpt?: boolean, threeOpt?: boolean}): { route: number[], distance: number }
Use it when you want the route to return to the starting point.
`distanceMatrix` must be a square array of arrays of numbers, such that `distanceMatrix[u][v]` is the length of the direct edge from city `u` to city `v`. `distanceMatrix[u][u]` will be ignored for all `u`. `optimizations` is an optional argument. When not given, it defaults to `{twoOpt: true, threeOpt: true}`.
Returns `{ route, distance }` where `route` is an optimal cycle consisting of *n* + 1 city numbers starting and ending with `0`, and `distance` is the length of the cycle.
#### getPath(distanceMatrix: number[][], optimizations?: {twoOpt?: boolean, threeOpt?: boolean}): { route: number[], distance: number }
Use it when you don't want the route to return to the starting point.
Similar to `getCycle`, returns `{ route, distance }` where `route` is an optimal path consisting of *n* city numbers, starting with `0`, and `distance` is the length of the path.
## Performance
For performance tests, run _e.g._
```sh
npm run perf -- 42
```
specifying whatever number of cities you wish. *n* cities will be placed randomly in a unit square, distances between them will be computed, then NN will be carried out to determine a cycle, capturing timings. Will show results for NN with no optimizations applied, NN with 2-opt only, NN with 3-opt only, and NN with both 2-opt and 3-opt.
In general:
- **Nearest Neighbour (NN) without optimizations** yields the fastest results but typically produces the least optimal solutions.
- **NN + 2-opt** significantly improves solution quality over NN alone, with minimal impact on performance.
- **NN + 3-opt** can sometimes find the better solution but is much slower—potentially up to 100x slower than NN + 2-opt.
- **NN + 2-opt + 3-opt** offers a good compromise, balancing improved solution quality with reasonable execution time. Its performance falls between NN + 2-opt and NN + 3-opt, and in some cases produces better results than NN + 3-opt.
### About this package
This package was created to support my personal project, [Moda Center Map](https://github.com/andrealvescorreia/moda-center-map), which provides routing functionality between multiple points of sale inside Moda Center—the largest wholesale clothing center in Brazil. The project required a fast and efficient way to calculate optimized routes locally on smartphones, but existing npm packages did not meet these needs. As a result, I developed this package to deliver low performance cost and close to optimal TSP solutions suitable for resource-constrained environments.