Every puzzle in Gooby has to follow two rules. It has exactly one solution, and you can reach that solution by reasoning, without guessing, using only the techniques its difficulty tier allows. A Sudoku with two solutions isn't a puzzle. And an "Easy" board that secretly needs an X-Wing is a bad experience.
This post walks through how the generators enforce those two rules for three of the games: Sudoku, Kakuro (cross sums) and Cagey (a KenKen-style maths grid). It's all Rust, and the code below is quoted from the repository.
Generate offline, ship static packs
The app never generates a puzzle while you play. A separate binary, packgen, builds puzzle packs ahead of time. Each pack is one file per game and tier (for example sudoku-hard.bin). Packs are plain static files that the service worker caches, which is part of why the games work offline.
Every game plugs into packgen through one trait in the shared core crate:
/// Offline generation and grading, used by `packgen` (and the server's validator).
pub trait Generate: Game {
/// Try once to produce a puzzle of the requested difficulty. `None` = retry.
fn generate(rng: &mut Rng, difficulty: Difficulty) -> Option<Self::Puzzle>;
/// Grade a puzzle with the technique solver. `None` if it is not uniquely solvable.
fn grade(p: &Self::Puzzle) -> Option<Grade>;
/// Canonical form for content-addressed ids and de-duplication.
fn canonical(p: &Self::Puzzle) -> String;
/// Full verification: unique solution, solution consistent, grade.
fn verify(p: &Self::Puzzle) -> Result<Grade, String>;
// ...
}
Two details in that trait matter.
generateis allowed to fail. Each call is one attempt from a seeded random number generator, and packgen calls it again until the pack is full. A generator doesn't need to be clever about hitting a target. It only needs to be honest when it misses.Gradecarries a tier, the name of the hardest technique the solve needed, and a score. Packgen sorts each pack by that score, so puzzles get gradually harder within a tier.
There are six tiers shared by every game: Easy, Medium, Hard, Expert, Master and Extreme. Each Sudoku tier has 200 puzzles. Kakuro and Cagey have 200, 200, 400, 400, 200 and 200.
Sudoku: dig holes, stop counting at two
Sudoku generation is the textbook approach. Fill a complete random grid. Then remove clues as long as the puzzle still has a single solution. Gooby removes them in pairs that mirror each other through the centre, which gives the half-turn symmetry people expect from a printed Sudoku:
pub fn generate(rng: &mut Rng, target: Difficulty) -> Option<(Vec<u8>, Vec<u8>)> {
let solution = random_solution(rng);
let mut puzzle = solution.clone();
let min_givens = match target {
Difficulty::Easy => rng.range(EASY_MIN_GIVENS, 40),
Difficulty::Medium => rng.range(28, 34),
_ => 17,
};
let mut order: Vec<usize> = (0..=40).collect();
rng.shuffle(&mut order);
let mut givens = N;
for c in order {
let mirror = N - 1 - c;
let removed = if c == mirror { 1 } else { 2 };
if givens - removed < min_givens {
continue;
}
let (a, b) = (puzzle[c], puzzle[mirror]);
puzzle[c] = 0;
puzzle[mirror] = 0;
if is_unique(&puzzle) {
givens -= removed;
} else {
puzzle[c] = a;
puzzle[mirror] = b;
}
}
let grade = grade_givens(&puzzle)?;
(grade.difficulty == target).then_some((puzzle, solution))
}
The uniqueness check runs once for every pair the generator tries to remove, so it has to be fast. It's a backtracking solver over bitmasks. Each row, column and box keeps a u16 of the digits it already uses, and the search always branches on the empty cell with the fewest options. The important trick is that it never counts every solution. It stops at two:
pub fn is_unique(grid: &[u8]) -> bool {
count_solutions(grid, 2) == 1
}
Once the search has found a second solution, it already knows the answer is "not unique", so there's no reason to keep looking.
Grading with a solver that thinks like a person
A backtracking solver proves uniqueness, but it says nothing about difficulty. For that, Gooby has a second solver that only uses techniques a person would use. It always takes the easiest step available:
pub const ORDER: &[(Technique, Finder)] = &[
(Technique::HiddenSingle, hidden_single),
(Technique::NakedSingle, naked_single),
(Technique::Pointing, pointing),
(Technique::Claiming, claiming),
(Technique::NakedPair, |g| naked_subset(g, 2)),
(Technique::HiddenPair, |g| hidden_subset(g, 2)),
(Technique::NakedTriple, |g| naked_subset(g, 3)),
(Technique::HiddenTriple, |g| hidden_subset(g, 3)),
(Technique::XWing, |g| fish(g, 2)),
(Technique::XYWing, xy_wing),
(Technique::NakedQuad, |g| naked_subset(g, 4)),
(Technique::HiddenQuad, |g| hidden_subset(g, 4)),
(Technique::Swordfish, |g| fish(g, 3)),
(Technique::XYZWing, xyz_wing),
];
The tier is set by the hardest technique the solve needed (the Sudoku techniques guide shows each one on a real Gooby puzzle):
| Tier | Hardest technique needed |
|---|---|
| Easy | Singles only, with at least 36 givens |
| Medium | Singles with fewer givens, pointing, claiming, naked pair |
| Hard | Hidden pair, naked or hidden triple |
| Expert | X-Wing, XY-Wing, quads |
| Master | Swordfish, XYZ-Wing |
| Extreme | Unique, but these 14 techniques can't finish it |
Each technique also has a weight, from 1 for a hidden single up to 22 for an XYZ-Wing. A puzzle's score is the sum of the weights of every step in its solve, and that score is what orders a pack.
The same solver also produces the hints. When you ask for one, the game walks next_step from your current position until it reaches a step that places a digit. It then explains that step in plain language, along with the eliminations that led to it. So the hints and the grading can't disagree: a hint only ever uses a technique the solver knows, and a puzzle's tier is based on those same techniques.
A grader is only useful if every technique is sound. One test generates 300 minimal puzzles from a fixed seed and checks that no step from any technique ever removes or places a digit that contradicts the true solution.
Kakuro: no givens, so dig holes the other way
You can't dig holes in a Kakuro, because a Kakuro has no givens to remove. The clues are the sums, and the sums come from the solution. So the generator runs the other way round. It builds a symmetric pattern of white runs, fills it with random digits, and then changes digits wherever the logical solver gets stuck. It keeps going until logic alone fills the board.
That last condition is also the uniqueness proof. Each technique only removes candidates that no solution can use. If the techniques shrink every square down to a single digit, then no other solution can exist. A board that logic completes has exactly one solution, and the generator never runs a solution-counting search.
Every Kakuro technique starts from one question: which sets of different digits add up to this clue? Gooby answers it with a lookup table of bitmasks, built once:
/// Digit sets (masks) of `len` different digits adding up to `sum`.
pub fn combos(len: usize, sum: u32) -> &'static [u16] {
use std::sync::OnceLock;
static TABLE: OnceLock<Vec<Vec<Vec<u16>>>> = OnceLock::new();
let t = TABLE.get_or_init(|| {
let mut t = vec![vec![vec![]; 46]; 10];
for m in 0u16..512 {
let mask = m << 1;
t[mask.count_ones() as usize][mask_sum(mask) as usize].push(mask);
}
t
});
t.get(len).and_then(|v| v.get(sum as usize)).map(|v| v.as_slice()).unwrap_or(&[])
}
There are only 511 non-empty subsets of 1–9, so the table is tiny. (The Kakuro guide prints the useful part of it as a combinations chart.) The techniques run in this order: Naked Single, Sum Combos, Must Have, Run Logic and What If. Run Logic tries every way of filling a run from its candidates. It doesn't list permutations. Instead it makes a forward and a backward pass over the subsets of digits already used.
In Kakuro, the board size sets the tier (6×6 for Easy up to 10×12 for Extreme). A board is kept only if its solve fits that tier's profile:
match d {
Difficulty::Easy => r.hardest <= Some(MustHave),
Difficulty::Medium => r.hardest <= Some(MustHave),
Difficulty::Hard => r.hardest <= Some(RunLogic) && (1..=4).contains(&u(RunLogic)),
Difficulty::Expert => r.hardest <= Some(RunLogic) && u(RunLogic) >= 3,
Difficulty::Master => u(RunLogic) >= 8 || u(WhatIf) >= 1,
Difficulty::Extreme => u(RunLogic) >= 12 || u(WhatIf) >= 1,
}
The Master and Extreme rules use "or" for a reason recorded in the project's decision log: a board that needs a What If and still has one solution is rare. A one-digit change to a board that logic can solve nearly always creates two pairs of squares that can swap, and that means two solutions. So the top tiers mostly mean long chains of Run Logic on big boards. The generator still makes 30 tries at a one-digit change that does need a What If.
Cagey: random cages, keep the ones that fit
Cagey is Gooby's KenKen-style game. Fill an n×n grid so that no number repeats in a row or column, and every cage's numbers make its target with its operation. The generator is the simplest of the three:
- Build a random Latin square (a backtracking fill with shuffled digits).
- Grow random connected cages over it. Cage sizes are drawn by weight for the tier, and a few one-square cages count as givens.
- Pick each cage's operation from its values. A two-square cage often gets ÷ when one value divides the other, and otherwise −, + or ×. Bigger cages get + or ×.
- Keep the board only if the techniques allowed in its tier can fill it.
pub fn generate(rng: &mut Rng, d: Difficulty) -> Option<(Layout, Vec<u8>)> {
let s = spec(d);
let sol = latin(rng, s.n);
for _ in 0..12 {
let cages = partition(rng, &s);
if cages.len() > crate::game::MAX_CAGES {
continue;
}
let lay = layout(s.n, &cages, &sol, rng);
// Logic filling the board proves the solution unique (see `grade`).
let r = solve(&lay, s.cap);
if fits(d, &r) {
return Some((lay, sol));
}
}
None
}
The argument is the same as in Kakuro. The techniques (Single Cage, Naked and Hidden Single, Cage Maths, Naked Subset, Cage Line and What If) only remove numbers that no solution can use, so a board they fill has one solution. The tier is the board size, from 4×4 for Easy to 9×9 for Extreme, and each tier also has a band of technique counts. A Hard board needs one to three Naked Subset or Cage Line steps. An Extreme board needs at least one What If.
Belt and braces: verify every pack in CI
"Logic finished it, so it's unique" is a proof, but it relies on every technique being correct. A bug in Run Logic or Cage Line would quietly produce puzzles with two solutions, and the same bug would make them look fine to the generator. So nothing ships on the generators' word alone. Every game also implements verify, which does a real search capped at two solutions, compares the result with the stored solution, and grades the puzzle again. Here is Kakuro's:
fn verify(p: &Puzzle) -> Result<Grade, String> {
let sols = search(&p.lay, 2);
if sols.len() != 1 {
return Err("not exactly one solution".into());
}
if sols[0] != p.solution {
return Err("stored solution does not match".into());
}
let (r, g) = generator::grade(&p.lay).ok_or("logic can't solve it")?;
if !generator::fits(g.difficulty, &r) {
return Err(format!("deductions don't fit {}: {:?}", g.difficulty.label(), r.uses));
}
Ok(g)
}
CI runs packgen verify over every shipped pack on every pull request:
cargo run --release -p pz-packgen -- verify --dir crates/app/public/packs
For every entry it decodes the puzzle and calls verify. It then checks that the graded tier matches the pack's tier and recomputes the puzzle's id from its canonical form. Ids are content-addressed (a hash of the canonical puzzle), so packgen can also drop a puzzle it has already generated.
What I'd keep if I started again
- Stop counting at two. Uniqueness checks run in the generator's inner loop, and "is there a second solution?" is much cheaper to answer than "how many solutions are there?".
- Make one solver do grading and hints. When the solver that grades a puzzle is also the one that explains the next step, a tier means something concrete: these are the techniques you'll need, and these are the ones the hints will teach.
- Let generators fail freely. An attempt that misses its tier just returns
None. Generation is offline, so wasted attempts cost build time, not the player's time. - When logic fills the board, uniqueness comes for free. For puzzles without givens, generating towards "logic can solve this" is both the uniqueness proof and the grade.
- Check again in CI. Every proof depends on code that can have bugs, and a full search capped at two solutions is a cheap second opinion.
If you want to see the result, every tier of all three games is free to play, with no ads and no account. When you get stuck, the hint names the technique you need.


