How a 9-Bit MRV Bitmask Engine Generates 100% Unique 9x9 Sudoku Grids in Under 1ms
DEV Community

How a 9-Bit MRV Bitmask Engine Generates 100% Unique 9x9 Sudoku Grids in Under 1ms

Most browser-based Sudoku sites cheat on puzzle generation. They either ship a megabyte of pre-baked static JSON grids or run a naive JavaScript backtracker built on nested arrays and Set allocations.

Pre-baked pools repeat eventually and lock players out of infinite fresh boards; naive backtrackers either freeze mobile frames or skip uniqueness verification altogether, silently serving broken grids with multiple valid solutions.

On Fogboard's Classic Sudoku 9x9, puzzle generation and uniqueness proofs happen live inside the browser tab in less than a millisecond - 0.15ms to 0.76ms on average, with a worst-case ceiling of 2.88ms across verified runs.

Achieving that speed in plain JavaScript without WebAssembly comes down to two classic systems techniques: packing every constraint into 9-bit Uint16Array bitmasks and driving the search tree with Minimum Remaining Values (MRV) pruning.

Packing Sudoku Constraints into 9-Bit Typed Arrays

In a standard 9x9 grid, every cell belongs to three constraint houses: one row, one column, and one 3x3 box. Checking whether digit d is legal at (r, c) by scanning three arrays takes up to 27 iterations per candidate test.

Instead, we represent the occupied digits of each house as a 9-bit integer stored inside flat Uint16Array buffers:

rows = new Uint16Array(9)
cols = new Uint16Array(9)
boxes = new Uint16Array(9)
grid = new Uint8Array(81)

Digit 1 maps to bit 0 (1 << 0), digit 2 maps to bit 1 (1 << 1), up through digit 9 at bit 8 (1 << 8). All nine digits combined equal 0x1FF (511 in decimal).

Finding every legal candidate for cell (r, c) in box b collapses into a single bitwise operation with zero heap allocations:

const ALL_DIGITS = 0x1ff; // 9 bits set: 0b1_1111_1111
const POPCOUNT = new Uint8Array(512);
for (let m = 1; m < 512; m++) {
  POPCOUNT[m] = POPCOUNT[m >> 1] + (m & 1);
}

function getCandidates(r: number, c: number, b: number, rows: Uint16Array, cols: Uint16Array, boxes: Uint16Array): number {
  return ALL_DIGITS & ~(rows[r] | cols[c] | boxes[b]);
}

Placing a digit flips one bit in each house via XOR (rows[r] ^= bit; cols[c] ^= bit; boxes[b] ^= bit). Undoing that placement on backtrack executes the exact same three XOR instructions. Because no temporary arrays or Set objects are created inside the recursive hot path, the JavaScript garbage collector stays completely idle during carving.

Minimum Remaining Values (MRV) and 2-Solution Early Abort

A fast bitmask lookup alone is still vulnerable to combinatorial blowup if the solver fills empty cells in fixed row-major order. Branching early on a cell with 7 legal digits multiplies the search tree unnecessarily.

MRV fixes this by scanning remaining empty cells and always picking the cell whose POPCOUNT[candidates] is smallest:

  • If any empty cell has candidates === 0, the current branch is an immediate dead end - backtrack at once.
  • If an empty cell has POPCOUNT[candidates] === 1, it is forced. The solver selects it immediately without scanning the rest of the board.
  • Otherwise, the solver branches on the tightest cell using lowest-set-bit extraction (const bit = mask & -mask; mask ^= bit;).

To carve a playable puzzle from a completed terminal grid, Fogboard shuffles all 81 cell indices and tests removing clues one by one. After tentatively clearing a cell, the MRV solver runs with a hard stop at limit = 2 solutions. The instant a second valid completion is found, the search aborts and restores the clue. If the solver exhausts the tree with solutions === 1, the removal is mathematically proven to preserve uniqueness.

Benchmarks and Architecture Comparison

The open methodology and test harness are published on Fogboard's solver verification and benchmarks page, confirming 100/100 uniquely verified grids per batch.

Comparing the three common web architectures highlights why typed bitmasks matter for client-side puzzle platforms:

Architecture Avg Generation Time Worst-Case Spike Uniqueness Guarantee Offline & Infinite Practice
Static JSON Pool 0ms (pre-baked) Network latency Depends on upstream dataset Limited by bundle size
Naive JS Array/Set DFS 15-120ms Greater than 500ms Often skipped to avoid lag Yes, with main-thread jank
Fogboard 9-Bit Uint16Array MRV 0.15-0.76ms 2.88ms 100/100 verified (2-abort) Yes, unlimited & instant

The same architecture scales cleanly down to Mini Sudoku 6x6, where 2x3 rectangular boxes use 6-bit masks (0x3F) across Easy through Hard difficulty tiers.

Deterministic 30-Day Archives Without a Server

Because generation is pure client-side math, Fogboard synchronizes daily puzzles across all 11 English games on its home tracker without storing daily boards in a backend database.

At 00:00 UTC each day, the UTC date string and game identifier are hashed with FNV-1a into a 32-bit seed, which drives a Mulberry32 pseudorandom number generator. That deterministic pipeline gives every visitor the exact same daily puzzle - and lets anyone replay any date across the built-in 30-day daily archive - with zero login and zero paywall.

Translating Bitmasks Into Human-Readable Hints

Sub-millisecond backtracking proves uniqueness, yet players rarely want a hint button that silently fills in a mystery number. On Classic Sudoku 9x9, the hint layer inspects the same candidate bitmasks to surface explainable human logic:

  • Naked Singles: Any empty cell whose candidate mask has POPCOUNT[mask] === 1 directly identifies the single digit that cannot be ruled out by its row, column, and box.
  • Hidden Singles: For each house and each digit bit 1 << d, if the bit appears in the candidate mask of only one empty cell within that row, column, or box, that cell must hold d + 1 regardless of its other candidates.

Paired with 3x3 pencil notes and automatic local progress saving, the interface bridges machine verification with readable deduction.

Honest Engineering Trade-Offs

Building an independent, zero-account browser engine comes with real trade-offs worth stating plainly:

  • Local-only storage: Auto-save, solve times, and 30-day archive completion badges stay inside browser local storage. There is no cross-device cloud sync, so progress started on a desktop workstation will not carry over to a phone, and clearing site data resets history.
  • Carving speed versus artisanal grading: MRV bitmask carving guarantees 100% mathematical uniqueness in sub-millisecond time, which is ideal for unlimited practice and deterministic dailies. By contrast, hand-crafted competition puzzles tuned around exotic chains like Swordfish or XY-Wings require slower multi-pass human-logic graders.

For developers curious about client-side constraint solving - or players who just want fast, verified boards without account gates - you can inspect the live benchmarks on How Solvers Work or stress-test the carving engine directly on Classic Sudoku 9x9.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.