tests/sims/dijkstra.test.ts
The automated tests for the /simulators/dijkstra-pathfinding simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- On 3,000 random graphs with non-negative weights, Dijkstra and Bellman-Ford give the same distances as Floyd-Warshall.
- Each shortest path Dijkstra reports is made of real edges and adds up to the reported distance.
- With negative weights, Bellman-Ford matches Floyd-Warshall and reports a reachable negative cycle as no answer.
// /simulators/dijkstra-pathfinding: Dijkstra and Bellman-Ford, against Floyd-Warshall.
import { test } from 'node:test';
import { dijkstra, bellmanFord, pathTo, GRAPHS, type Graph } from '../../src/lib/sims/dijkstra.ts';
import { checker, lcg } from './check.ts';
function randomGraph(r: () => number, directed: boolean, minW: number): Graph {
const n = 2 + Math.floor(r() * 9);
const nodes = Array.from({ length: n }, (_, i) => ({ id: String.fromCharCode(65 + i), x: 0, y: 0 }));
const edges = [];
for (let a = 0; a < n; a++) for (let b = directed ? 0 : a + 1; b < n; b++) if (a !== b && r() < 0.35) edges.push({ a: nodes[a].id, b: nodes[b].id, w: minW + Math.floor(r() * (10 - minW)) });
return { id: 'rand', name: 'rand', directed, nodes, edges, source: 'A', target: nodes[n - 1].id };
}
// all-pairs shortest paths by Floyd-Warshall; negative-cycle nodes get -Infinity
function floyd(g: Graph) {
const ids = g.nodes.map((n) => n.id), ix = new Map(ids.map((id, i) => [id, i])), n = ids.length;
const d = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 0 : Infinity)));
for (const e of g.edges) {
const a = ix.get(e.a)!, b = ix.get(e.b)!;
d[a][b] = Math.min(d[a][b], e.w);
if (!g.directed) d[b][a] = Math.min(d[b][a], e.w);
}
for (let k = 0; k < n; k++) for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
const s = ix.get(g.source)!;
const negCycle = ids.some((_, v) => d[v][v] < 0 && d[s][v] < Infinity);
return { dist: Object.fromEntries(ids.map((id, j) => [id, d[s][j]])), negCycle };
}
test('on 3,000 random graphs with non-negative weights, Dijkstra and Bellman-Ford give the same distances as Floyd-Warshall', () => {
const { ok, done } = checker();
const r = lcg(13);
const graphs = [...GRAPHS.filter((g) => g.edges.every((e) => e.w >= 0)), ...Array.from({ length: 3000 }, (_, i) => randomGraph(r, i % 2 === 0, 0))];
for (const g of graphs) {
const ref = floyd(g).dist, d = dijkstra(g, g.source).final.dist, bf = bellmanFord(g, g.source);
for (const id of Object.keys(ref)) {
ok(d[id] === ref[id], `${g.id} ${g.directed ? 'directed' : 'undirected'}: Dijkstra says ${id} is ${d[id]}, Floyd-Warshall ${ref[id]}`);
ok(bf !== null && bf[id] === ref[id], `${g.id}: Bellman-Ford says ${id} is ${bf?.[id]}, Floyd-Warshall ${ref[id]}`);
}
}
done();
});
test('each shortest path Dijkstra reports is made of real edges and adds up to the reported distance', () => {
const { ok, done } = checker();
const r = lcg(14);
for (let i = 0; i < 2000; i++) {
const g = randomGraph(r, i % 2 === 0, 0), run = dijkstra(g, g.source).final;
for (const n of g.nodes) {
if (run.dist[n.id] === Infinity) continue;
const p = pathTo(run.prev, n.id);
ok(p[0] === g.source && p.at(-1) === n.id, `path to ${n.id} does not run from ${g.source}`);
let sum = 0;
for (let k = 1; k < p.length; k++) {
const w = Math.min(...g.edges.filter((e) => (e.a === p[k - 1] && e.b === p[k]) || (!g.directed && e.b === p[k - 1] && e.a === p[k])).map((e) => e.w));
ok(w < Infinity, `no edge ${p[k - 1]}-${p[k]}`);
sum += w;
}
ok(sum === run.dist[n.id], `path to ${n.id} weighs ${sum}, distance says ${run.dist[n.id]}`);
}
}
done();
});
test('with negative weights, Bellman-Ford matches Floyd-Warshall and reports a reachable negative cycle as no answer', () => {
const { ok, done } = checker();
const r = lcg(15);
let cycles = 0;
for (let i = 0; i < 3000; i++) {
const g = randomGraph(r, true, -3), ref = floyd(g), bf = bellmanFord(g, g.source);
if (ref.negCycle) { cycles++; ok(bf === null, 'a negative cycle went unreported'); continue; }
ok(bf !== null && Object.keys(ref.dist).every((id) => bf[id] === ref.dist[id]), 'Bellman-Ford distances differ from Floyd-Warshall');
}
ok(cycles > 100, `only ${cycles} graphs had a negative cycle, too few to test that case`);
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.