Chapter 6
KenKen
KenKen is Sudoku with arithmetic. The grid is again an Latin square: each row and each column a permutation of . Layered on top, the grid is partitioned into cages, each carrying an arithmetic clue: the cells in a cage must combine, by addition, multiplication, subtraction, or division, to a target value declared in the cage’s top-left corner.
The puzzle was invented by the Japanese mathematics teacher Tetsuya Miyamoto in , originally as a teaching device for elementary-school students learning arithmetic; he called it kashikoku naru puzzle ("a puzzle that makes you smarter"). The Tokyo publisher Gakken adopted it and renamed it KenKen, short for kenkou ken’i, "wisdom and cleverness". Among many trademarked variants in English-speaking markets it goes by Calcudoku, Mathdoku, and the New York Times’ KenKen.
The constraint set extends Sudoku in the cleanest possible way: the two all-different families remain, and every cage contributes one further equation. The arithmetic is local; the all-differents are global. CP-SAT’s AddMultiplicationEquality and AddAbsEquality primitives make the cage clues a few lines each. The result is a model that, like Sudoku, scales smoothly from a teaching example to the puzzles that test computer solvers.
Rules and a small instance
A KenKen puzzle is an grid. Each cell holds a digit from to . The grid is partitioned into cages: each cage is a connected polyomino of one or more cells, and each carries an arithmetic clue.
Each row contains each digit from to exactly once.
Each column contains each digit from to exactly once.
For each cage with target and operator , the cell values combine under to . Singleton cages carry only a target and force the cell to hold .
The arithmetic conventions need a moment. For addition and multiplication the cage’s cells combine in the natural order-free way: their sum or product equals the target. For subtraction and division, which are not commutative, the convention is to take the absolute difference (subtraction) or the larger divided by the smaller (division), so the order of cells in the cage does not matter. By tradition, subtraction and division cages contain exactly two cells.
Figure 6.1 shows a KenKen with nine cages, including two singleton "givens" that are KenKen’s analogue of Sudoku starter clues.
The programming model
Let for . The Latin square base reuses the Sudoku constraints:
Each cage with target , operator , and cell set contributes one further constraint:
The product and difference constraints need a touch of CP-SAT plumbing. AddMultiplicationEquality ties an auxiliary variable to the product of a list of variables in one call; AddAbsEquality ties an auxiliary to the absolute value of a single variable, used for the difference cage. The quotient cage uses two reified linear constraints under a Boolean indicator choosing which of the two cells is the dividend.
A solver in thirty lines
from ortools.sat.python import cp_model
def solve_kenken(n, cages):
"""cages: list of (op, target, [(r, c), ...]).
op in {'+', '*', '-', '/', '='}."""
m = cp_model.CpModel()
x = [[m.NewIntVar(1, n, f"x{r}{c}")
for c in range(n)] for r in range(n)]
for r in range(n):
m.AddAllDifferent(x[r])
for c in range(n):
m.AddAllDifferent([x[r][c] for r in range(n)])
for op, t, cells in cages:
vs = [x[r][c] for r, c in cells]
if op == '+':
m.Add(sum(vs) == t)
elif op == '*':
p = m.NewIntVar(1, n**len(vs), "")
m.AddMultiplicationEquality(p, vs)
m.Add(p == t)
elif op == '-':
d = m.NewIntVar(-n, n, "")
ad = m.NewIntVar(0, n, "")
m.Add(d == vs[0] - vs[1])
m.AddAbsEquality(ad, d)
m.Add(ad == t)
elif op == '/':
a, b = vs
pick = m.NewBoolVar("")
m.Add(a == t * b).OnlyEnforceIf(pick)
m.Add(b == t * a).OnlyEnforceIf(pick.Not())
elif op == '=':
m.Add(vs[0] == t)
s = cp_model.CpSolver()
ok = s.Solve(m)
if ok not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
raise RuntimeError("no solution")
return [[s.Value(x[r][c])
for c in range(n)] for r in range(n)]
The toy of Figure 6.1 solves in about milliseconds and admits a single completion.
A hard instance
Figure 6.3 is the instance from the recreational maths archive, billed as the hardest KenKen recorded there. Thirty-three cages of mixed operator and length sit on top of the Latin square base; the largest sums extend across five cells, the largest product is over four cells. CP-SAT returns the unique solution (Figure 6.4) in about milliseconds.
The propagation that makes the hard puzzle tractable is again the all-different constraint working in tandem with cage-local arithmetic. A cage like product over four cells, on a grid, has the factorisations , and a small handful of others over digits to ; CP-SAT enumerates these implicitly and prunes early.
Sources. KenKen was invented by Tetsuya Miyamoto in and first published by Gakken in Japan as kashikoku naru puzzle. The puzzle reached an English audience through Will Shortz, the New York Times’ crossword editor, in . Robert Fuhrer’s KenKen Puzzle LLC holds the trademark; Calcudoku and Mathdoku are widely-used free names for the same puzzle. The hard instance is sourced from the recreational mathematics archive accompanying this book; its CP-SAT formulation matches the original Z model constraint by constraint.