Calcudoku generator in Python: most random puzzles have a second answer
Random cages over a random square gave a puzzle with exactly one answer only about 40% of the time, at 4 x 4, 5 x 5 and 6 x 6 alike. The common shortcut for the square makes it look better or worse, depending on the size.
A calcudoku, also sold as KenKen, is a Latin square split into cages: each row and column holds 1 to n once, and each cage shows a target and an operation, such as 12× for two squares whose product is 12. To make one in Python you draw a square, cut it into cages and write each cage's clue from the numbers inside. That always gives a puzzle the square solves. It does not always give a puzzle only the square solves.
On 31 October 2026 we drew random puzzles at three sizes and counted, for each, every square that fits its clues.
The short version#
- One answer: 44% of 400 random 4 x 4 puzzles, 41% of 300 at 5 x 5, 40% of 100 at 6 x 6. The rest had two or more.
- The fix is a filter: keep the square, redraw the cages and clues until exactly one answer fits. That took 4.1 draws on average at 4 x 4, 2.2 at 5 x 5 and 3.8 at 6 x 6, 1.1 to 1.3 s a puzzle at 6 x 6 over two runs.
- The shortcut that skews it: many generators shuffle the rows, columns and numbers of a cyclic square (1 2 3 4 / 2 3 4 1 ...). At 5 x 5 that kind of square has no 2 x 2 corners that can swap, and 73% of its puzzles had one answer. At 6 x 6 it has 9 on average, and only 22% did.
The code#
import random
from functools import reduce
from itertools import permutations
def latin_square(n, rng=random):
"""A random n x n square where each row and column holds 1..n once: random rows, each kept only if it clashes
with no row above it in any column; start over if a row cannot be found."""
rows = []
while len(rows) < n:
for _ in range(5000):
row = rng.sample(range(1, n + 1), n)
if all(row[c] != above[c] for above in rows for c in range(n)):
rows.append(row)
break
else:
rows = []
return rows
def cages(n, rng=random, most=4):
"""Split the grid into connected cages of 1 to `most` squares."""
free, out = {(r, c) for r in range(n) for c in range(n)}, []
while free:
cell = min(free)
cage, size = [cell], rng.choice([1, 2, 2, 3, 3, 4][:2 + most])
free.discard(cell)
while len(cage) < size:
nexts = [(r + dr, c + dc) for r, c in cage for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0))
if (r + dr, c + dc) in free]
if not nexts:
break
cell = rng.choice(nexts)
cage.append(cell)
free.discard(cell)
out.append(cage)
return out
def clue(values, rng=random):
"""(operation, target) for a cage's values: - and / only for two squares, / only when it divides evenly."""
if len(values) == 1:
return "=", values[0]
a, b = max(values), min(values)
ops = ["+", "*"] + (["-"] + (["/"] if a % b == 0 else []) if len(values) == 2 else [])
op = rng.choice(ops)
return op, {"+": sum(values), "*": reduce(lambda x, y: x * y, values), "-": a - b, "/": a // b if b else 0}[op]
def fits(op, target, values):
if op == "=":
return values[0] == target
if op == "+":
return sum(values) == target
if op == "*":
return reduce(lambda x, y: x * y, values) == target
a, b = max(values), min(values)
return a - b == target if op == "-" else a == b * target
def count_answers(n, puzzle, stop=2):
"""How many squares fit the cages (stops at `stop`): fill row by row with permutations of 1..n, prune each cage
as soon as it is complete."""
cage_of = {cell: i for i, (cells, op, t) in enumerate(puzzle) for cell in cells}
last = {i: max(cells) for i, (cells, op, t) in enumerate(puzzle)} # the cage is complete at this cell
grid, found = [], [0]
def go(r, used_cols):
if found[0] >= stop:
return
if r == n:
found[0] += 1
return
for row in permutations(range(1, n + 1)):
if any(row[c] in used_cols[c] for c in range(n)):
continue
grid.append(row)
ok = True
for c in range(n):
i = cage_of[r, c]
if last[i] == (r, c):
cells, op, t = puzzle[i]
if not fits(op, t, [grid[y][x] for y, x in cells]):
ok = False
break
if ok:
go(r + 1, [used_cols[c] | {row[c]} for c in range(n)])
grid.pop()
go(0, [set() for _ in range(n)])
return found[0]
def make(n, rng=random, tries=500):
"""A square and cages whose clues have exactly one answer: redraw the cages and clues until they do."""
square = latin_square(n, rng)
for k in range(1, tries + 1):
puzzle = [(cells, *clue([square[r][c] for r, c in cells], rng)) for cells in cages(n, rng)]
if count_answers(n, puzzle) == 1:
return square, puzzle, k
raise RuntimeError("no puzzle with one answer")square, puzzle, tries = make(4, random.Random(2))
for cells, op, target in puzzle:
print(f"{target}{op if op != '=' else ''}", cells)
print("cage draws:", tries, "| answers:", count_answers(4, puzzle))With that seed the second draw of cages had one answer: seven cages, clues from 3 (a single square) to 16× (four squares).
Where second answers come from#
The usual cause is a 2 x 2 corner of the square that reads a b over b a. Swap the two numbers in those four squares and every row and column is still fine. If each cage that touches the corner holds both squares of one of its rows or columns (or all four), every clue still fits, because a + b, a × b, a − b and a ÷ b do not depend on the order, and the puzzle has a second answer. Our latin_square() had 5.3 such corners on average at 4 x 4, 3.7 at 5 x 5 and 8.0 at 6 x 6.
The cyclic shortcut changes that count in a way that depends only on the size: 0 at 5 x 5 (odd sizes have none), 4 at 4 x 4, 9 at 6 x 6. So a generator built on it looks better than it is at 5 x 5 and worse at 6 x 6, and either way its squares come from a small family. Building rows at random and keeping those that fit, as latin_square() does, avoids both.
Counting answers#
count_answers() fills the grid row by row with every ordering of 1 to n that does not repeat a number in a column, and checks each cage as soon as its last square is filled. It stops at 2, because the question is only "one, or more than one". At 6 x 6 that took about 0.1 s for half the puzzles and up to about 3 s for the slowest. Bigger grids need a smarter solver; the counting idea stays the same.
One answer is the minimum. Books also grade puzzles by how they can be solved: a puzzle with one answer can still need a guess. That takes a second solver that works the way a person does, step by step.
A whole book, not one grid#
Our calcudoku book maker makes both checks on every puzzle: a second program, written apart from the one that makes the puzzles, finds exactly one finished grid for the cage clues, and each puzzle is solved again step by step with no guessing, with harder steps only at the harder levels. Every cage is one connected group of up to 4 squares, products stay at three digits or fewer, and the full solutions are at the back. Easy books use 6 x 6 grids, medium 7 x 7 and hard 8 x 8, and the book is checked against KDP's paperback specs before you can download it.
written
6 min readSamurai sudoku generator in Python: one answer for the board is not enough
A samurai sudoku is five grids that share corner boxes. A generator that only asks for one answer for the whole board left boards where none of the five grids had one answer on its own. Asking it of every grid costs about 14 more starting digits and made the generator 12 times faster.
13 min readKiller sudoku generator in Python: cut the cages until logic solves it
Random cages over a finished grid had exactly one answer in 2 of 60 tries, and logic alone solved none. Cutting cages until logic solves the puzzle works, and the rule of 45 takes it from 218 grids a puzzle to 9.
7 min readSkyscrapers puzzle generator in Python: the edge numbers are rarely enough
All 20 edge numbers of a 5 x 5 skyscrapers grid fix the answer for only 42 % of grids, and only 8 % of our random 6 x 6 grids. A generator then has to print some heights. Printing one where two answers differ needs about a third as many as printing random ones.