Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 24
Module 9 · Design problems VI: social, trading and puzzles · Chapter 24 of 28
Jigsaw Puzzle: Pieces, Edges, Fitting and a Solver
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps and Design Patterns in TypeScript: Creational, Structural and Behavioural. Next up: Airline Management: Flights, Seats, Bookings and Crew.
Part 1 · Requirements and use cases
What the puzzle must do
A jigsaw puzzle is a search problem with a picture on top: every piece has four edges, and only some pieces fit in some places. This chapter models pieces and edges, checks a piece against its neighbours and solves a small puzzle by backtracking.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does, and we write them before any class exists. Everything here is our model of a puzzle, which is simpler than a cardboard one: there is no picture, only the shapes of the edges.
- A puzzle is a rectangle of at least one row and one column of cells, and each cell takes one piece. A size of zero, a negative size or a fraction is refused.
- A piece has four edges: top, right, bottom and left. An edge is flat, a tab (a bump) or a blank (a socket), and a tab or a blank has a shape number.
- Two touching edges fit when one is a tab and the other is a blank of the same shape. A flat edge fits nothing.
- A piece on the border of the board has its flat edge on the outside. No flat edge may face the inside.
- A piece can be turned in quarter turns clockwise, from 0 to 3, when it is placed.
- A player takes a piece from the box, places it at a cell with a turn, and can lift a placed piece back to the table.
- A placement is refused when the cell is taken, outside the board or has an edge that does not fit. A refused piece stays on the table.
- The puzzle is complete when every cell holds a piece.
- The program can solve a puzzle, suggest a piece for the next empty cell and report progress.
| Question | If the answer is yes | Our answer |
|---|---|---|
| Can a placed piece be turned in place? |
Quality and scope
Non-functional requirements say how well the system behaves. A refused placement must change nothing: the piece stays on the table and the board is as it was. The solver must stop, which means it returns a board that is complete or reports that none exists, and when it fails it must leave the board empty again. And demos must give the same output on every run, so randomness is injected and seeded.
We rejected two designs. The first stores a piece's position inside the piece. Moving a piece then means updating the piece and the board, and the two can disagree. We keep positions on the board only. The second keeps four rotated copies of every piece. It makes fitting a plain comparison, but a puzzle of nine pieces turns into thirty-six, and the solver has to remember that four of them are one piece. We keep one piece and a rotation number, and let rotation be a small calculation.
| Must | Should | Out of scope |
|---|---|---|
| Pieces, edges, turns, take, place, lift, fit check, complete board, solver | Index for faster solving, hints, progress | Pictures, irregular boards, drag and drop, time limits |
Use cases
An actor is someone outside the system who uses it, and a use case is one goal an actor wants to reach. The puzzle has one actor, the player. A use case diagram shows the actor, the use cases and how they relate. Include means a use case always runs another as part of itself, and extend means an exceptional case adds steps under a condition. Placing a piece always includes taking it from the box. A piece that does not fit extends placing.
The blue box is the actor and the pills are use cases, with the refusal in red. An arrow from the actor means the actor starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". Formal UML draws the extend arrow the other way, from the extension to the base; here the label carries the meaning.
"Solve the puzzle" sits beside the actor because it is a single request: the program does the searching. Each use case gets a written flow.
| Use case | Main flow | Alternatives |
|---|---|---|
| Place a piece | Take it from the box, choose a cell and a turn, check, put it down | Taken, outside, bad turn, edge mismatch: refuse, piece stays on the table |
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name, a map of the work that is reported but not run, and each one becomes a real test by the end.
test.todo('a player places a piece'); test.todo('a player lifts a piece'); test.todo('a player asks for a hint'); test.todo('a player sees the progress'); test.todo('a player solves the puzzle');
✔ a player places a piece (0.859ms) # TODO ✔ a player lifts a piece (0.121ms) # TODO ✔ a player asks for a hint (0.0958ms) # TODO ✔ a player sees the progress (0.1004ms) # TODO ✔ a player solves the puzzle (0.1129ms) # TODO ℹ tests 5 ℹ todo 5
Output (durations vary)
All five names are reported as todo, and none counts as passed. If a name never gets a test, the requirement behind it was probably missed.
Check yourself
A flat edge faces an empty cell in the middle of the board. Is the placement allowed?
- No. In our model a flat edge belongs on the outside of the board, so it may not face the inside.
What is the difference between include and extend in the diagram?
- Include: placing always runs taking the piece from the box.
- Extend: a refusal adds steps only when the piece does not fit.
Why does the solver have to leave the board empty when it fails?
- A failed search must not leave half a solution behind that later calls would treat as real.
Part 2 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: puzzle, cell, piece, edge, tab, blank, shape, turn, board, box, table, player, hint, progress. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Puzzle | Class Puzzle | Owns the pieces and where each one is: box, table or board |
| Board | Class Board | Holds the placed pieces and decides whether a piece may go in a cell |
| Piece | Interface Piece | An id and four edges, never changed |
| Edge | Interface Edge | A kind and a shape number |
| Edge kind | String union EdgeKind | Three fixed values |
| Turn | A number from 0 to 3 | Only an index shift, kept beside the placement |
| Placement | Interface Placement | Row, column and turn |
| Box, table | PieceState in Puzzle | Two values of a piece's state, not places |
| Solver | Functions solve, cellOrder | Take a board and pieces, keep no state |
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 1 means exactly one, 4 means four, and 0..* means any number, including none.
board: Boardtake(id), lift(id)place(id, row, col, rotation)state(id): box, table, placedpieces(): Piece[]rows, colscanPlace(piece, row, col, rot): Problem?place(...), remove(row, col)at(row, col), isComplete()idedges: four Edge, top firstkind: flat, tab or blankshape: numberrow, colrotation: 0 to 3cellOrder(rows, cols, mode)solve(board, pieces, order, stats)int(min, max)int(min, max)same numbers for one seed- Puzzle 1 → 1 Board
- Puzzle 1 → 1..* Piece
- Piece 1 → 4 Edge
- Board 1 → 0..* Piece
- Board 1 → 0..* Placement (value)
- Solver (functions) → Board
- Seeded → Random (interface)
One Puzzle owns one Board and one or more pieces. Each piece has exactly four edges. The board holds any number of placed pieces, each with its turn. The solver works on a board and a list of pieces, which is why its arrow points to Board. The arrow from Seeded to Random means "is a kind of", and the arrow from the solver to Board means "uses".
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We start with the types: the kinds of edge, the four sides and the piece.
export type EdgeKind = 'flat' | 'tab' | 'blank'; // A tab fits a blank of the same shape. A flat edge fits nothing. export interface Edge { readonly kind: EdgeKind; readonly shape: number; } // Sides are numbered clockwise from the top: 0 top, 1 right, // 2 bottom, 3 left. export type Side = 0 | 1 | 2 | 3; export interface Piece { readonly id: string; readonly edges: readonly [Edge, Edge, Edge, Edge]; }
The placement and the errors follow. Every refusal is a PuzzleError with a code, so callers and tests branch on the code and never on the message.
// Where a piece sits, and its clockwise quarter turns. export interface Placement { readonly row: number; readonly col: number; readonly rotation: number; }
export type PuzzleCode = | 'BAD_SIZE' | 'UNKNOWN_PIECE' | 'NOT_IN_BOX' | 'NOT_ON_TABLE' | 'NOT_PLACED' | 'OUT_OF_BOUNDS' | 'CELL_TAKEN' | 'BAD_ROTATION' | 'EDGE_MISMATCH'; export class PuzzleError extends Error { readonly code: PuzzleCode; constructor(code: PuzzleCode, message: string) { super(message); this.name = 'PuzzleError'; this.code = code; } }
Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
The skeleton compiles. A side is a number from 0 to 3, going clockwise from the top, so side 1 is the right and side 3 is the left. The type Side is a union of those four numbers, which means that a function that takes a side cannot be given a 4 by mistake.
Why are the box and the table states of a piece and not classes?
- A piece is always in exactly one of three states, and nothing else needs a list of the box.
- A state is one field to update, so a piece cannot be in two places.
Why is the solver a function and not a class?
- It keeps no state between calls: it takes a board and pieces and fills the board.
Part 3 · Placing a piece
Piece states
A state machine lists the states, the events that cause moves and the events a state refuses. A piece has three states. box is where every piece starts. table is a piece the player has taken and not placed. placed is a piece on the board. Three events move it: take, place and lift.
Watch for the piece staying on the table after a refusal
Read it as steps
A refused piece stays on the table, and the board does not change.
The scene takes P1 from the box and tries to place it with no turn. The placement is refused with EDGE_MISMATCH, and the piece stays on the table. The player then turns it three times and it is placed in the top left corner. The refusal is the important part: a refused piece must not be half placed.
| State | take | place | lift |
|---|---|---|---|
| box | to table | refused | refused |
| table |
The neighbour check
When a piece is placed, the board looks at all four sides of the cell. Each side asks one of three questions. If the side is on the outside of the board, the piece's edge must be flat. If a placed piece is next to it, the two edges must fit. If an empty cell is next to it, the piece's edge must not be flat.
Watch for the board checking every side of the piece
Read it as steps
The board checks all four sides. Turn 0 fails on the right side and turn 3 fits.
The scene is P1 in the top left corner. With no turn, its top edge is flat, which is right for the border, but its right edge is flat too and a cell lies to its right, so the board refuses it. Turns 1 and 2 are refused on the top side, and the run in the next page shows all four tries. With turn 3 the flat edges face the top and the left, and the placement is accepted.
| Step | Can fail with | Changes anything? |
|---|---|---|
| Is the cell inside the board | OUT_OF_BOUNDS | No |
| Is the cell free | CELL_TAKEN |
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. It builds a 3 by 3 puzzle from a fixed seed, so it is the same on every run, and it places the three pieces of the top row. The answer key that the generator also returns is used only to choose which pieces to show. A real player has no key.
// The answer key picks which pieces to show; a real player has no key. const byCell = (row: number, col: number) => pieces.find((p) => { const a = answer.get(p.id)!; return a.row === row && a.col === col; })!; for (const [row, col] of [[0, 0], [0, 1], [0, 2]] as const) { const piece = byCell(row, col); const sides = [0, 1, 2, 3] as Side[]; const edges = sides.map((s) => show(edgeAt(piece, s, 0))); puzzle.take(piece.id); console.log(`${piece.id} on the table, edges ${edges.join(' ')}`);
for (let rot = 0; rot < 4; rot++) { const bad = puzzle.board.canPlace(piece, row, col, rot); if (bad) { const at = SIDES[bad.side!]; console.log(` turn ${rot}: ${bad.code}, ${at} edge`); continue; } puzzle.place(piece.id, row, col, rot); console.log(` turn ${rot}: placed at (${row},${col})`); break; } } console.log(`placed ${puzzle.board.placed} of 9`);
P1 on the table, edges flat flat tab6 blank1 turn 0: EDGE_MISMATCH, right edge turn 1: EDGE_MISMATCH, top edge turn 2: EDGE_MISMATCH, top edge turn 3: placed at (0,0) P2 on the table, edges flat tab5 tab18 blank6 turn 0: placed at (0,1) P3 on the table, edges flat flat blank10 blank5 turn 0: placed at (0,2) placed 3 of 9
Output
Read the output. P1 has two flat edges, top and right, and a blank on the left. With no turn the right edge is flat but a cell lies on the right, so it is refused on the right side. Turns 1 and 2 put a non-flat edge on the top, which is refused on the top side. With turn 3 the flat edges face the top and the left, and the piece is placed. P2 fits with no turn, because its left blank meets the tab on P1's right. P3 does too, and it ends the row with a flat edge on the right. Three pieces are placed.
Why is the refused piece left on the table and not returned to the box?
- The player has already taken it, so it is in the player's hand and can be tried again.
- Returning it would add a move that nobody asked for.
Part 4 · Code: rotation, fitting and a solver
Rotation and fitting
A turn changes nothing about a piece. It changes which of the piece's four edges faces which side. After one quarter turn clockwise, the edge that was on top is on the right. So after r turns, the edge on side s is the one that was on side s - r, counted round the four sides.
// After r clockwise quarter turns, the edge that was on side s - r // is on side s. Rotation is only an index shift. export function edgeAt(p: Piece, side: Side, rotation: number): Edge { return p.edges[(side - rotation + 4) % 4]!; }
The + 4 keeps the number positive for small turns, and % 4 wraps it round. Fitting is the other half. A tab fits a blank of the same shape in either order, and nothing else fits anything.
export function fits(a: Edge, b: Edge): boolean { const pair = (a.kind === 'tab' && b.kind === 'blank') || (a.kind === 'blank' && b.kind === 'tab'); return pair && a.shape === b.shape; }
test('turning is an index shift, one quarter turn at a time', () => { assert.equal(edgeAt(piece, 0, 0), piece.edges[0]); // after one clockwise turn the top edge is on the right assert.equal(edgeAt(piece, 1, 1), piece.edges[0]); assert.equal(edgeAt(piece, 0, 1), piece.edges[3]); assert.equal(edgeAt(piece, 2, 2), piece.edges[0]); }); test('three turns: right edge on top, top edge on the left', () => { assert.equal(edgeAt(piece, 0, 3), piece.edges[1]); assert.equal(edgeAt(piece, 3, 3), piece.edges[0]); }); test('a tab fits a blank of the same shape, in either order', () => { assert.equal(fits(tab(3), blank(3)), true); assert.equal(fits(blank(3), tab(3)), true); });
✔ turning is an index shift, one quarter turn at a time (0.5647ms) ✔ three turns: right edge on top, top edge on the left (0.1011ms) ✔ a tab fits a blank of the same shape, in either order (0.1082ms) ✔ other pairs do not fit (0.0939ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
The first test spells out the rule for a few sides. After one turn the top edge is on the right and the left edge is on top. After three turns the right edge is on top. The fit tests list the pairs that do not fit: different shapes, two tabs, two blanks and a flat edge with anything.
The board check
The board's check is the three questions from the last lesson, side by side. A table of the four steps and a loop over the four sides is the whole function.
// Undefined means the piece may go here. Nothing is changed. canPlace(p: Piece, row: number, col: number, rot: number) { if (!this.inside(row, col)) return no('OUT_OF_BOUNDS'); if (this.at(row, col)) return no('CELL_TAKEN'); if (!Number.isInteger(rot) || rot < 0 || rot > 3) { return no('BAD_ROTATION'); } for (const side of SIDES) { const mine = edgeAt(p, side, rot); const r = row + STEP[side][0]; const c = col + STEP[side][1]; const next = this.at(r, c);
The first three guards return a problem and no side. Then the loop looks at each side. STEP holds the row and column offsets of the four neighbours, so the neighbour of side s is at row + STEP[s][0] and col + STEP[s][1].
let ok: boolean; if (!this.inside(r, c)) { ok = mine.kind === 'flat'; } else if (next) { const facing = ((side + 2) % 4) as Side; ok = fits(mine, edgeAt(next.piece, facing, next.rotation)); } else { ok = mine.kind !== 'flat'; } if (!ok) return no('EDGE_MISMATCH', side); } return undefined; }
If the neighbour cell is on the outside, the edge must be flat. If a piece is there, its edge on the facing side, which is two sides round, must fit ours. If the cell is empty, our edge must not be flat. The first failing side is returned in the problem, which is how the driver could print "right edge".
test('a corner piece fits its corner with the right turn', () => { const board = new Board(2, 2); assert.equal(board.canPlace(A, 0, 0, 0), undefined); assert.equal(board.canPlace(A, 0, 0, 1)!.code, 'EDGE_MISMATCH'); }); test('a flat edge may not face an empty cell inside the board', () => { const board = new Board(2, 2); const bad = board.canPlace(B, 0, 0, 0)!; assert.deepEqual(bad, { code: 'EDGE_MISMATCH', side: 1 }); }); test('neighbours must fit, tab to blank of the same shape', () => { const board = new Board(2, 2); board.place(A, 0, 0, 0); assert.equal(board.canPlace(B, 0, 1, 0), undefined); const wrong: Piece = { id: 'W', edges: [FLAT, FLAT, blank(3), blank(9)], }; assert.equal(board.canPlace(wrong, 0, 1, 0)!.side, 3); });
✔ a corner piece fits its corner with the right turn (0.7953ms) ✔ a flat edge may not face an empty cell inside the board (0.5093ms) ✔ neighbours must fit, tab to blank of the same shape (0.1812ms) ✔ the outside, taken cells and bad turns are refused (0.1546ms) ✔ a refused placement changes nothing (0.5458ms) ✔ the board is complete when every cell is filled (0.2027ms) ✔ a board needs at least one row and one column (0.1977ms) ✔ a fractional cell is outside the board (0.2111ms) ℹ tests 8 ℹ pass 8 ℹ fail 0
Output (durations vary)
The solver
Solving is a search. Fill the cells one at a time in some order. For the next cell, try every piece that is not used, in each of the four turns. If one fits, place it and move on to the next cell. If the rest of the board cannot be filled, take the piece back and try the next choice. That take-back is backtracking.
// Backtracking: fill cells in order, trying every unused piece in every // rotation, and undo the last choice when nothing fits. export function solve( board: Board, pieces: readonly Piece[], order: readonly Cell[], stats: Stats = { attempts: 0 }, ): boolean { const used = new Set<string>(); const fill = (i: number): boolean => { if (i === order.length) return true; const [row, col] = order[i]!; for (const p of pieces) { if (used.has(p.id)) continue; for (let rot = 0; rot < 4; rot++) { stats.attempts++; if (board.canPlace(p, row, col, rot)) continue; board.place(p, row, col, rot); used.add(p.id); if (fill(i + 1)) return true; board.remove(row, col); used.delete(p.id); } } return false; }; return fill(0); }
stats.attempts counts how often canPlace is called. That is the measure we use to compare solvers, because it does not depend on the speed of the machine. When fill gets past the last cell it returns true all the way up, and the board is complete. When every choice fails, each level has already removed its piece, so a failed search leaves the board as it found it. The solver expects an empty board to start with.
The order of the cells matters. We give two. rows goes row by row, so each new piece has a neighbour above and on the left. borders goes corners first, then the other border cells, then the inside, which is a common idea because flat edges are rare and make strong clues.
// The order in which cells are filled. export function cellOrder( rows: number, cols: number, mode: 'rows' | 'borders', ): Cell[] { const all: Cell[] = []; for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) all.push([r, c]); } if (mode === 'rows') return all; // How many sides are on the border: corners 2, edges 1, inside 0. const rank = ([r, c]: Cell) => { const rowEdge = r === 0 || r === rows - 1; const colEdge = c === 0 || c === cols - 1; return 2 - Number(rowEdge) - Number(colEdge); }; return [...all].sort((a, b) => rank(a) - rank(b)); }
Testing the solver
The tests build puzzles with the generator, which cuts a finished picture along random joints and returns pieces in a shuffled box with their turns scrambled. Because the puzzle is built from a finished picture, a solution exists. The answer key is a valid solution too, and a test replays it. The solver tests then check complete boards from many seeds, using a separate check that does not trust canPlace: it walks the board and tests every touching pair with fits.
test('the answer key is a valid solution', () => { const { answer, pieces, puzzle } = rig(); for (const p of pieces) { const a = answer.get(p.id)!; puzzle.take(p.id); puzzle.place(p.id, a.row, a.col, a.rotation); } assert.equal(puzzle.board.isComplete(), true); assert.equal(everyJointFits(puzzle.board), true); });
test('both orders solve 3 by 3 puzzles from many seeds', () => { for (let seed = 1; seed <= 25; seed++) { for (const mode of ['rows', 'borders'] as const) { const { pieces } = rig(seed); const board = new Board(3, 3); assert.equal(solve(board, pieces, cellOrder(3, 3, mode)), true); assert.equal(board.isComplete(), true); assert.equal(everyJointFits(board), true); } } }); test('a puzzle with a piece missing has no solution', () => { const { pieces } = rig(); const board = new Board(3, 3); const found = solve(board, pieces.slice(1), cellOrder(3, 3, 'rows')); assert.equal(found, false); assert.equal(board.placed, 0); });
✔ the answer key is a valid solution (2.2164ms) ✔ cells are ordered corners, then edges, then the inside (0.6581ms) ✔ both orders solve 3 by 3 puzzles from many seeds (4.5129ms) ✔ a puzzle with a piece missing has no solution (0.2218ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
The seeded test solves twenty-five puzzles in each of the two orders and checks all of them. The last test removes a piece, so no full board is possible. The solver returns false, and the board has no piece left on it. Random shapes can repeat, so a puzzle may have more than one solution, which is why the tests check that a board is valid and not that it equals the key.
After two quarter turns clockwise, which edge of a piece is on the top?
- The one that was on the bottom. Side 0 shows the edge at index
(0 - 2 + 4) % 4, which is 2.
What does stats.attempts count, and why not time?
Part 5 · Extensions and trade-offs
Every use case, tested
The use case lesson left five test.todo names. The rest of the chapter lives in a copy of the project with new files added: a hint, a progress count and a faster solver. With them, each todo becomes a real test that drives the use case the way the player would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
test('a player places a piece', () => { const { puzzle } = rig(); const o = hint(puzzle)!.options[0]!; puzzle.take(o.id); puzzle.place(o.id, 0, 0, o.rotation); assert.equal(puzzle.state(o.id), 'placed'); assert.equal(puzzle.board.placed, 1); }); test('a player lifts a piece', () => { const { puzzle } = rig(); const o = hint(puzzle)!.options[0]!; puzzle.take(o.id); puzzle.place(o.id, 0, 0, o.rotation); puzzle.lift(o.id); assert.equal(puzzle.state(o.id), 'table'); assert.equal(puzzle.board.placed, 0); });
test('a player asks for a hint', () => { const { puzzle } = rig(); const h = hint(puzzle)!; assert.deepEqual([h.row, h.col], [0, 0]); assert.ok(h.options.length >= 1); }); test('a player sees the progress', () => { const { puzzle } = rig(); assert.equal(progress(puzzle).percent, 0); }); test('a player solves the puzzle', () => { const { pieces } = rig(); const board = new Board(3, 3); assert.equal(solve(board, pieces, cellOrder(3, 3, 'rows')), true); assert.equal(board.isComplete(), true); });
✔ a player places a piece (1.0705ms) ✔ a player lifts a piece (0.2047ms) ✔ a player asks for a hint (0.6297ms) ✔ a player sees the progress (0.1414ms) ✔ a player solves the puzzle (0.3838ms) ℹ tests 5 ℹ pass 5 ℹ fail 0 ℹ todo 0
Output (durations vary)
Five pass and no todo is left. The whole extended project, with every earlier test, also passes.
ℹ tests 31 ℹ pass 31 ℹ fail 0 ℹ todo 0
Output: whole suite
An index from edges to pieces
The plain solver tries every unused piece in every turn at each cell, and nearly all of them fail on the first side checked. An index is a lookup table built once so that a question can be answered without scanning everything. Here the question is "which pieces, in which turns, have this top edge and this left edge?". When we fill row by row, the top and left neighbours are already placed, so their edges name exactly what the new piece needs. A tab on a neighbour's bottom needs a blank of the same shape on our top.
const name = (e: Edge): string => e.kind === 'flat' ? 'flat' : `${e.kind}${e.shape}`; // The edge that would mate with e. const mate = (e: Edge): string => `${e.kind === 'tab' ? 'blank' : 'tab'}${e.shape}`; // Every piece in every rotation, filed under its top and left edge. export function buildIndex(pieces: readonly Piece[]) { const index = new Map<string, Option[]>(); for (const piece of pieces) { for (let rotation = 0; rotation < 4; rotation++) { const key = `${name(edgeAt(piece, 0, rotation))}|` + name(edgeAt(piece, 3, rotation)); const list = index.get(key) ?? []; list.push({ piece, rotation }); index.set(key, list); } } return index; }
The key is the two edge names joined by a bar. The solver asks for the key built from the neighbours, or flat where there is no neighbour, and tries only the pieces it gets back. canPlace still runs on each one, because the right and bottom edges are not part of the key.
const fill = (i: number): boolean => { if (i === order.length) return true; const [row, col] = order[i]!; const above = board.at(row - 1, col); const before = board.at(row, col - 1); const top = above ? mate(edgeAt(above.piece, 2, above.rotation)) : 'flat'; const left = before ? mate(edgeAt(before.piece, 1, before.rotation)) : 'flat'; const found = index.get(`${top}|${left}`) ?? []; for (const { piece, rotation } of found) { if (used.has(piece.id)) continue; stats.attempts++; if (board.canPlace(piece, row, col, rotation)) continue; board.place(piece, row, col, rotation); used.add(piece.id); if (fill(i + 1)) return true; board.remove(row, col); used.delete(piece.id); } return false; }; return fill(0);
Counting attempts
We now compare the three solvers on the same puzzles. For each size, twenty seeded puzzles are solved by the plain solver in the two cell orders and by the indexed solver, and the numbers of canPlace calls are added up. The shapes are drawn from twice as many numbers as there are pieces, so most shapes are unique.
// Attempts are calls to canPlace, summed over 20 seeded puzzles. for (const n of [4, 5, 6]) { const total = { rows: 0, borders: 0, indexed: 0 }; for (let seed = 1; seed <= 20; seed++) { const make = () => makePuzzle(n, n, n * n * 2, new Seeded(seed)); for (const mode of ['rows', 'borders'] as const) { const stats = { attempts: 0 }; const { pieces } = make(); solve(new Board(n, n), pieces, cellOrder(n, n, mode), stats); total[mode] += stats.attempts; } const stats = { attempts: 0 }; solveIndexed(new Board(n, n), make().pieces, stats); total.indexed += stats.attempts; } const row = `${n}x${n}`.padEnd(5); console.log(`${row} rows ${total.rows}, borders ${total.borders}, ` + `indexed ${total.indexed}`); }
4x4 rows 5839, borders 19215, indexed 330 5x5 rows 12789, borders 35693, indexed 508 6x6 rows 27310, borders 74726, indexed 744
Output (a count of calls, the same on every run)
The indexed solver makes a few hundred checks where the plain one makes thousands. Read the second column next. Going corners first was meant to help, and here it makes the search about three times worse than going row by row. A likely reason is that a row-by-row search places every piece beside a neighbour, so a wrong choice is found at once. A border-first search places many pieces with no placed neighbour, so almost anything with a flat edge in the right place is accepted, and the mistake is found much later. That result is about our rules and these puzzles, not a law. We also ran 4 by 4 puzzles with only 3 distinct shapes: the totals rose to 19,347 for rows and 45,407 for borders, so the order of the two did not change here, but the counts did. Measure before you adopt a clever order.
Hints, progress and weak spots
A hint is the first empty cell, in row order, and every piece and turn that would fit there. Progress is a count of placed cells against all cells. Both are small functions over the puzzle and the board.
export function progress(puzzle: Puzzle) { const total = puzzle.board.rows * puzzle.board.cols; const placed = puzzle.board.placed; return { placed, total, percent: Math.floor((placed * 100) / total) }; } // The first empty cell, and every piece and turn that would fit there. export function hint(puzzle: Puzzle) { const { board } = puzzle; for (let row = 0; row < board.rows; row++) { for (let col = 0; col < board.cols; col++) { if (board.at(row, col)) continue; const options: { id: string; rotation: number }[] = []; for (const p of puzzle.pieces()) { if (puzzle.state(p.id) === 'placed') continue; for (let rotation = 0; rotation < 4; rotation++) { if (!board.canPlace(p, row, col, rotation)) { options.push({ id: p.id, rotation }); } } } return { row, col, options }; } } return undefined; }
test('a hint lists only pieces and turns that fit', () => { const { puzzle } = rig(); const h = hint(puzzle)!; assert.deepEqual([h.row, h.col], [0, 0]); assert.ok(h.options.length > 0); const first = h.options[0]!; puzzle.take(first.id); puzzle.place(first.id, h.row, h.col, first.rotation); assert.equal(puzzle.state(first.id), 'placed'); }); test('a hint moves on to the next empty cell', () => { const { puzzle } = rig(); const first = hint(puzzle)!.options[0]!; puzzle.take(first.id); puzzle.place(first.id, 0, 0, first.rotation); const next = hint(puzzle)!; assert.deepEqual([next.row, next.col], [0, 1]); assert.ok(next.options.every((o) => o.id !== first.id)); });
test('progress counts placed pieces', () => { const { puzzle } = rig(); const none = { placed: 0, total: 9, percent: 0 }; assert.deepEqual(progress(puzzle), none); const o = hint(puzzle)!.options[0]!; puzzle.take(o.id); puzzle.place(o.id, 0, 0, o.rotation); const one = { placed: 1, total: 9, percent: 11 }; assert.deepEqual(progress(puzzle), one); });
✔ the index solver finds a complete, valid board (3.2996ms) ✔ the index tries far fewer pieces than the plain solver (0.5603ms) ✔ a hint lists only pieces and turns that fit (0.621ms) ✔ a hint moves on to the next empty cell (0.2966ms) ✔ progress counts placed pieces (0.2309ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
Every design has costs. The solver works on a board and does not move pieces through the box and table states, so a solved board and the state of each piece can disagree. Fitting only checks edges, so a real puzzle with a picture would need a second check, and a bad cut could make an ambiguous puzzle. Backtracking is exponential in the worst case: the counts above stay small because most shapes are unique, and with fewer shapes the same puzzles cost several times more checks. And the board is a plain array of cells, which fits a rectangle and would not fit an irregular shape.
All chapters · Previous: Online Stock Brokerage: Orders, Order Book, Matching and Portfolio