tests/sims/segtree.test.ts
The automated tests for the /simulators/segment-tree 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.
- Range queries match a direct scan after point sets and lazy range adds, visiting at most 4 nodes per level.
// /simulators/segment-tree
import { test } from 'node:test';
import { SegTree, type Agg } from '../../src/lib/sims/segtree.ts';
import { checker, lcg } from './check.ts';
test('range queries match a direct scan after point sets and lazy range adds, visiting at most 4 nodes per level', () => {
const { ok, done } = checker();
const r = lcg(5);
for (const agg of ['sum', 'min', 'max'] as Agg[]) for (let trial = 0; trial < 200; trial++) {
const n = 1 + Math.floor(r() * 40);
const a = Array.from({ length: n }, () => Math.floor(r() * 41) - 20);
const t = new SegTree(a, agg);
for (let k = 0; k < 60; k++) {
const x = Math.floor(r() * n), y = Math.floor(r() * n), l = Math.min(x, y), rr = Math.max(x, y);
const p = r();
if (p < 0.5) {
const res = t.run({ kind: 'query', l, r: rr });
const seg = a.slice(l, rr + 1);
const want = agg === 'sum' ? seg.reduce((u, v) => u + v, 0) : agg === 'min' ? Math.min(...seg) : Math.max(...seg);
ok(res.value === want, `${agg} of [${l}, ${rr}]: ${res.value} vs ${want}`);
ok(res.visited <= 4 * t.depth(), `visited ${res.visited} nodes, more than 4 per level`);
} else if (p < 0.75) {
const v = Math.floor(r() * 41) - 20;
t.run({ kind: 'set', i: x, v });
a[x] = v;
} else {
const v = Math.floor(r() * 11) - 5;
t.run({ kind: 'add', l, r: rr, v });
for (let i = l; i <= rr; i++) a[i] += v;
}
ok(t.values().join() === a.join(), `${agg}: stored values drifted from the array`);
}
}
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.