Worked solutions to the three exercises of Lecture 10. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: Knuth's (2000) canonical {1..7} trace and sensor-zone partitioning")
mm19 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 19][0]
print(f"Mental Move #{mm19['id']} ({mm19['name']}): {mm19['invariant']}")
# 1. Donald Knuth's (2000) 'Dancing Links' paper exact example on universe {1, 2, 3, 4, 5, 6, 7}:
knuth_u = [1, 2, 3, 4, 5, 6, 7]
knuth_subs = {
"A": [1, 4, 7],
"B": [1, 4],
"C": [4, 5, 7],
"D": [3, 5, 6],
"E": [2, 3, 6, 7],
"F": [2, 7],
}
res_knuth = reductions_constraints.exact_cover_algorithm_x(knuth_u, knuth_subs)
assert res_knuth["solution_count"] == 1
assert sorted(res_knuth["solutions"][0]) == ["B", "D", "F"] # {1,4} U {3,5,6} U {2,7} = {1..7}!
# 2. Engineering reduction: Partitioning 8 reactor monitoring zones across non-interfering sensor modules:
zones = [f"Z{i}" for i in range(1, 9)]
radio_channels = ["CH_alpha", "CH_beta", "CH_gamma", "CH_delta"] # Secondary mutex: at most 1 module per channel
sensor_modules = {
"Mod_NorthA": ["Z1", "Z2", "Z5", "CH_alpha"],
"Mod_NorthB": ["Z1", "Z2", "CH_beta"],
"Mod_EastA": ["Z3", "Z4", "CH_beta"],
"Mod_EastB": ["Z3", "Z4", "Z6", "CH_alpha"],
"Mod_SouthA": ["Z5", "Z7", "Z8", "CH_gamma"],
"Mod_SouthB": ["Z6", "Z7", "Z8", "CH_delta"],
"Mod_WestA": ["Z5", "Z6", "CH_gamma"],
"Mod_Core": ["Z7", "Z8", "CH_delta"],
}
res_sens = reductions_constraints.exact_cover_algorithm_x(zones, sensor_modules, secondary_elements=radio_channels)
assert res_sens["solution_count"] == 2
for sol in res_sens["solutions"]:
covered_z = [e for k in sol for e in sensor_modules[k] if e.startswith("Z")]
used_ch = [e for k in sol for e in sensor_modules[k] if e.startswith("CH_")]
assert sorted(covered_z) == sorted(zones) # Every zone covered ONCE
assert len(used_ch) == len(set(used_ch)) # Every radio channel used AT MOST ONCE
print(f"Knuth {{1..7}} exact cover : {res_knuth['solutions']} found in {res_knuth['search_nodes']} search nodes")
print(f"Reactor sensor deployments : {res_sens['solutions']} (verified zero zone overlap & zero radio collisions)")
# Visualize Knuth's binary incidence matrix A and highlight exact-cover rows B, D, F:
row_names = list(knuth_subs.keys())
inc_mat = np.zeros((len(row_names), len(knuth_u)), dtype=int)
for r_i, rk in enumerate(row_names):
for elem in knuth_subs[rk]:
inc_mat[r_i, elem - 1] = 2 if rk in ("B", "D", "F") else 1
fig, ax = plt.subplots(figsize=(6.8, 3.6))
ax.imshow(inc_mat, cmap="YlGnBu", aspect="auto", vmin=0, vmax=2)
ax.set_xticks(range(7))
ax.set_xticklabels([str(x) for x in knuth_u])
ax.set_yticks(range(len(row_names)))
ax.set_yticklabels([f"{rk} {'<- COVER' if rk in ('B','D','F') else ''}" for rk in row_names])
ax.set_xlabel(r"Primary universe element $e \in \{1..7\}$")
ax.set_ylabel("Candidate subset")
ax.set_title("Knuth's example: rows B, D and F cover every column once")
ax.grid(False)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Compile domino and 3-cell L-tromino tilings of boards into exact_cover_algorithm_x. Verify (a) Kasteleyn’s exact count of 36 domino tilings on , (b) 0 domino tilings when opposite same-color corners (0,0) and (3,3) are deleted vs. >0 when (0,0) and (0,3) are deleted, and (c) exact L-tromino tilability of all 16 single-defect boards.
heading("Exercise 1: Domino and L-tromino exact cover + mutilated checkerboard parity invariant")
def build_domino_exact_cover(n_rows: int, n_cols: int, forbidden: set[tuple[int, int]] | None = None) -> dict:
forb = set() if forbidden is None else set(forbidden)
cells = [(r, c) for r in range(n_rows) for c in range(n_cols) if (r, c) not in forb]
subs: dict[str, list] = {}
for r, c in cells:
if (r, c + 1) in cells:
subs[f"H({r},{c})"] = [(r, c), (r, c + 1)]
if (r + 1, c) in cells:
subs[f"V({r},{c})"] = [(r, c), (r + 1, c)]
return reductions_constraints.exact_cover_algorithm_x(cells, subs, max_solutions=200)
# (a) Intact 4x4 domino tilings == Kasteleyn (1961) closed-form analytical formula (36):
kast_4x4 = 1.0
for j in range(1, 3):
for k in range(1, 3):
kast_4x4 *= 4.0 * math.cos(j * math.pi / 5.0) ** 2 + 4.0 * math.cos(k * math.pi / 5.0) ** 2
dom_intact = build_domino_exact_cover(4, 4)
assert int(round(kast_4x4)) == 36 and dom_intact["solution_count"] == 36
# (b) Mutilated 4x4 board: removing same-color corners (0,0) and (3,3) leaves 6 even-parity and 8 odd-parity cells
cells_same = [(r, c) for r in range(4) for c in range(4) if (r, c) not in {(0, 0), (3, 3)}]
white_cnt = sum(1 for r, c in cells_same if (r + c) % 2 == 0)
black_cnt = sum(1 for r, c in cells_same if (r + c) % 2 == 1)
assert white_cnt == 6 and black_cnt == 8 # Every domino covers 1 white + 1 black -> impossible
dom_mutilated_same = build_domino_exact_cover(4, 4, forbidden={(0, 0), (3, 3)})
dom_mutilated_opp = build_domino_exact_cover(4, 4, forbidden={(0, 0), (0, 3)})
assert dom_mutilated_same["solution_count"] == 0
assert dom_mutilated_opp["solution_count"] > 0
# (c) Golomb's L-tromino theorem: every 2^k x 2^k board missing ANY 1 cell can be tiled by L-trominoes
l_orientations = [
[(0, 0), (0, 1), (1, 0)],
[(0, 0), (0, 1), (1, 1)],
[(0, 0), (1, 0), (1, 1)],
[(0, 1), (1, 0), (1, 1)],
]
for r_def in range(4):
for c_def in range(4):
active_cells = [(r, c) for r in range(4) for c in range(4) if (r, c) != (r_def, c_def)]
cell_set = set(active_cells)
t_subs = {}
for r in range(3):
for c in range(3):
for o_i, offsets in enumerate(l_orientations):
tri = [(r + dr, c + dc) for dr, dc in offsets]
if all(pt in cell_set for pt in tri):
t_subs[f"L{o_i}({r},{c})"] = tri
res_t = reductions_constraints.exact_cover_algorithm_x(active_cells, t_subs, max_solutions=10)
assert res_t["solution_count"] >= 1
print(f"Intact 4x4 domino tilings : {dom_intact['solution_count']} (Kasteleyn analytical formula = {kast_4x4:.1f})")
print(f"Mutilated same-color (0,0)&(3,3) : {dom_mutilated_same['solution_count']} solutions (W={white_cnt}, B={black_cnt} parity obstruction)")
print(f"Mutilated opposite-color (0,0)&(0,3): {dom_mutilated_opp['solution_count']} solutions")
print("Golomb L-tromino tilability verified across all 16 single-cell defect positions on 4x4")
Exercise 1: Domino and L-tromino exact cover + mutilated checkerboard parity invariant
======================================================================================
Intact 4x4 domino tilings : 36 (Kasteleyn analytical formula = 36.0)
Mutilated same-color (0,0)&(3,3) : 0 solutions (W=6, B=8 parity obstruction)
Mutilated opposite-color (0,0)&(0,3): 12 solutions
Golomb L-tromino tilability verified across all 16 single-cell defect positions on 4x4
Explanation. Coloring cell by forces every domino to cover one white and one black cell (). Deleting opposite corners (0,0) and (3,3) removes two white cells ( and are both even), leaving 6 white and 8 black cells. Seven dominoes would have to cover 7 white cells, so no tiling exists.
Exercise 2¶
Problem. Verify all ValueError input guards on exact_cover_algorithm_x, reduce_n_queens_to_exact_cover, and reduce_latin_square_completion, then demonstrate (a) why making -Queens diagonals primary constraints returns 0 solutions for all , and (b) how omitting cell(r,c) constraints in Latin-square reduction produces multi-symbol cell collisions.
heading("Exercise 2: Failure-mode audit — guards, primary-diagonal bug and missing cell constraints")
# 0. Input guard checks:
caught = 0
for bad_fn in [
lambda: reductions_constraints.exact_cover_algorithm_x([1, 2], {"A": [1]}, max_solutions=0),
lambda: reductions_constraints.exact_cover_algorithm_x([1, 2], {"A": [1]}, secondary_elements=[2]),
lambda: reductions_constraints.exact_cover_algorithm_x([1, 2], {"A": [1, 99]}),
lambda: reductions_constraints.reduce_n_queens_to_exact_cover(0),
lambda: reductions_constraints.reduce_latin_square_completion(np.zeros((1, 1), dtype=int)),
lambda: reductions_constraints.reduce_latin_square_completion(np.array([[0, 5], [1, 2]])),
]:
try:
bad_fn()
except ValueError:
caught += 1
assert caught == 6
# (a) Buggy N-Queens reduction: putting diagonals into primary_elements instead of secondary_elements
for n_q in [4, 5, 6, 8]:
prim_bug = (
[f"R{r}" for r in range(n_q)]
+ [f"C{c}" for c in range(n_q)]
+ [f"D1_{d}" for d in range(-(n_q - 1), n_q)]
+ [f"D2_{s}" for s in range(2 * n_q - 1)]
)
subs_q = {f"Q({r},{c})": [f"R{r}", f"C{c}", f"D1_{r-c}", f"D2_{r+c}"] for r in range(n_q) for c in range(n_q)}
res_bug = reductions_constraints.exact_cover_algorithm_x(prim_bug, subs_q, max_solutions=10)
res_ok = reductions_constraints.reduce_n_queens_to_exact_cover(n_q, max_solutions=10)
assert res_bug["solution_count"] == 0 and res_ok["solution_count"] > 0
# (b) Buggy Latin-square reduction omitting cell(r, c) primary uniqueness constraints:
n_lat = 3
prim_no_cell = [f"row({r},{v})" for r in range(n_lat) for v in range(1, n_lat + 1)] + [f"col({c},{v})" for c in range(n_lat) for v in range(1, n_lat + 1)]
# Fix clues forcing (0,0)=1 AND (0,0)=2 simultaneously if cell(0,0) mutex is forgotten
subs_no_cell = {
f"({r},{c})={v}": [f"row({r},{v})", f"col({c},{v})"]
for r in range(n_lat) for c in range(n_lat) for v in range(1, n_lat + 1)
}
res_nc = reductions_constraints.exact_cover_algorithm_x(prim_no_cell, subs_no_cell, max_solutions=200)
# Find a 'solution' that stacked MULTIPLE values into the same cell (r, c) while leaving another cell empty
corrupted = [
sol for sol in res_nc["solutions"]
if len({tok.split("=")[0] for tok in sol}) < n_lat * n_lat
]
assert len(corrupted) > 0
print("Guard checks passed : 6/6 invalid Exact Cover / N-Queens / Latin inputs raised ValueError.")
print("Bug (a) Primary diagonals on 8-Queens : 0 solutions (2*8 - 1 = 15 diagonals cannot all hold 1 of 8 queens)")
print(f"Bug (b) Omitting cell(r,c) on 3x3 : Produced {len(corrupted)} corrupted grids stacking multiple symbols in one cell (e.g. {corrupted[0][:4]})")
Exercise 2: Failure-mode audit — guards, primary-diagonal bug and missing cell constraints
==========================================================================================
Guard checks passed : 6/6 invalid Exact Cover / N-Queens / Latin inputs raised ValueError.
Bug (a) Primary diagonals on 8-Queens : 0 solutions (2*8 - 1 = 15 diagonals cannot all hold 1 of 8 queens)
Bug (b) Omitting cell(r,c) on 3x3 : Produced 188 corrupted grids stacking multiple symbols in one cell (e.g. ['(0,0)=1', '(1,1)=1', '(2,2)=1', '(0,0)=2'])
Explanation. (a) An board has main diagonals, yet row/column uniqueness allows at most queens on the entire board. Marking diagonals primary demands queens simultaneously with queens—an instant pigeonhole contradiction for every . (b) Without cell(r,c) primary columns, placing 1, 2, and 3 all inside (0,0), (1,1), and (2,2) while leaving the other 6 cells blank satisfies every row(r,v) and col(c,v) sum.
Exercise 3¶
Problem. Implement reduce_mini_sudoku_4x4(clue_grid, max_solutions=300) compiling Mini-Sudoku into 64 primary columns (16 cell + 16 row + 16 col + 16 box) and solving via exact_cover_algorithm_x. Verify: (i) an empty grid has exactly 288 valid Sudoku completions, (ii) a 6-clue puzzle has two completions and becomes unique (solution_count == 1) when a seventh clue is added, and (iii) a box-conflict grid yields 0 solutions.
heading("Exercise 3: Implement it yourself — compiling 4x4 mini-Sudoku into 64-column exact cover")
def reduce_mini_sudoku_4x4(clue_grid: np.ndarray, max_solutions: int = 300) -> dict:
"""Compile a 4x4 Mini-Sudoku (0 = blank, 1..4 = clue) into 64 Exact Cover primary constraints."""
g = np.asarray(clue_grid, dtype=int)
if g.shape != (4, 4) or np.any((g < 0) | (g > 4)):
raise ValueError("Require (4, 4) integer clue_grid with entries in 0..4.")
primary = (
[f"cell({r},{c})" for r in range(4) for c in range(4)]
+ [f"row({r},{v})" for r in range(4) for v in range(1, 5)]
+ [f"col({c},{v})" for c in range(4) for v in range(1, 5)]
+ [f"box({b},{v})" for b in range(4) for v in range(1, 5)]
)
assert len(primary) == 64
subsets: dict[str, list[str]] = {}
for r in range(4):
for c in range(4):
b = 2 * (r // 2) + (c // 2)
vals = [int(g[r, c])] if g[r, c] > 0 else [1, 2, 3, 4]
for v in vals:
subsets[f"({r},{c})={v}"] = [f"cell({r},{c})", f"row({r},{v})", f"col({c},{v})", f"box({b},{v})"]
res = reductions_constraints.exact_cover_algorithm_x(primary, subsets, max_solutions=max_solutions)
grids = []
for sol in res["solutions"]:
mat = np.zeros((4, 4), dtype=int)
for tok in sol:
rc_s, v_s = tok.split("=")
r_i, c_i = rc_s.strip("()").split(",")
mat[int(r_i), int(c_i)] = int(v_s)
grids.append(mat)
return {"grids": grids, "solution_count": res["solution_count"], "search_nodes": res["search_nodes"]}
# 1. Exact enumerative combinatorics benchmark: empty 4x4 Mini-Sudoku has 4 * 12 = 288 valid grids
all_4x4 = reduce_mini_sudoku_4x4(np.zeros((4, 4), dtype=int), max_solutions=350)
assert all_4x4["solution_count"] == 288
# 2. Under-constrained 6-clue puzzle (2 completions) vs. disambiguated 7-clue unique puzzle (1 completion):
puzzle_two = np.array([
[1, 2, 3, 0],
[3, 0, 1, 0],
[2, 0, 0, 0],
[0, 0, 0, 0],
], dtype=int)
res_two = reduce_mini_sudoku_4x4(puzzle_two)
assert res_two["solution_count"] == 2 # Exactly 2 symmetric bottom-half completions
puzzle_unique = puzzle_two.copy()
puzzle_unique[3, 3] = 1
res_uniq = reduce_mini_sudoku_4x4(puzzle_unique)
assert res_uniq["solution_count"] == 1
sol_u = res_uniq["grids"][0]
for i in range(4):
assert sorted(sol_u[i, :].tolist()) == [1, 2, 3, 4]
assert sorted(sol_u[:, i].tolist()) == [1, 2, 3, 4]
for br in (0, 2):
for bc in (0, 2):
assert sorted(sol_u[br : br + 2, bc : bc + 2].ravel().tolist()) == [1, 2, 3, 4]
# 3. Box-conflict invalid puzzle (valid Latin clues, but two 1s inside top-left 2x2 box):
bad_box = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
], dtype=int)
assert reduce_mini_sudoku_4x4(bad_box)["solution_count"] == 0
print(f"Total valid 4x4 Mini-Sudoku boards : {all_4x4['solution_count']} (exact combinatorics = 288)")
print(f"7-clue unique puzzle solved in : {res_uniq['search_nodes']} search nodes ->\n{sol_u}")
print("2x2 box-conflict detection : 0 solutions returned in 1 root check")
Exercise 3: Implement it yourself — compiling 4x4 mini-Sudoku into 64-column exact cover
========================================================================================
Total valid 4x4 Mini-Sudoku boards : 288 (exact combinatorics = 288)
7-clue unique puzzle solved in : 17 search nodes ->
[[1 2 3 4]
[3 4 1 2]
[2 1 4 3]
[4 3 2 1]]
2x2 box-conflict detection : 0 solutions returned in 1 root check
Summary. Upgrading a Latin-Square solver into a full Sudoku solver needs no change to exact_cover_algorithm_x, only the addition of 'box(b, v)' to each candidate tuple. The value of solution_count also classifies the puzzle (0 = inconsistent clues, 1 = well-posed unique puzzle, >1 = under-constrained).