About: how pages are checked

tests/sims/nqueens.test.ts

The automated tests for the /simulators/n-queens-backtracking 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.

  1. Solution counts for n = 1 to 13 match OEIS A000170, with and without the mirror-symmetry shortcut.
  2. The step-by-step backtracker visits the same number of nodes as the fast counter, and its boards are valid.
  3. Min-conflicts ends on a valid board, up to 1,000 queens.
// /simulators/n-queens-backtracking: backtracking and min-conflicts, against the published solution counts.
import { test } from 'node:test';
import { backtrack, count, valid, minConflicts } from '../../src/lib/sims/nqueens.ts';
import { checker } from './check.ts';

// OEIS A000170: number of ways to place n non-attacking queens on an n x n board
const A000170 = [1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712];

test('solution counts for n = 1 to 13 match OEIS A000170, with and without the mirror-symmetry shortcut', () => {
	const { ok, done } = checker();
	A000170.forEach((want, i) => {
		const n = i + 1;
		ok(count(n).solutions === want, `n=${n}: ${count(n).solutions}, OEIS says ${want}`);
		ok(count(n, true).solutions === want, `n=${n} with symmetry: ${count(n, true).solutions}`);
	});
	done();
});

test('the step-by-step backtracker visits the same number of nodes as the fast counter, and its boards are valid', () => {
	const { ok, done } = checker();
	for (let n = 1; n <= 10; n++) {
		const b = backtrack(n), c = count(n);
		ok(b.solutions === c.solutions && b.nodes === c.nodes, `n=${n}: ${b.solutions} solutions / ${b.nodes} nodes vs ${c.solutions} / ${c.nodes}`);
		ok(b.first.every(valid), `n=${n}: an invalid board`);
	}
	done();
});

test('min-conflicts ends on a valid board, up to 1,000 queens', () => {
	const { ok, done } = checker();
	for (const n of [8, 50, 200, 1000]) for (const seed of [1, 2, 3]) for (const greedy of [true, false]) {
		const m = minConflicts(n, seed, greedy);
		ok(m.moves >= 0 && valid(m.board), `n=${n} seed ${seed}${greedy ? '' : ' random start'}`);
	}
	done();
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published