s LearnSqueak.com

SMALLTALK LAB

Sudoku candidates: propagate constraints without guessing

Model a 4-by-4 Sudoku with peer sets, eliminate forbidden digits, and repeat naked singles to a fixed point. Keep solved, stuck and contradictory boards distinct, preserve inputs and test the solver in native Squeak.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use a native Squeak 6.1 Workspace. Select one complete checkpoint and choose Print it. All eight checkpoints are independent and install no classes. The grid is an indexed collection of sixteen integers, stored row by row; 0 means blank. The separate Morphic board runs with Do it: set stage from 0 through 4 to inspect candidates and three computed waves.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.

01 - Represent a small Sudoku with one flat array

Use digits 1 through 4 and four 2-by-2 boxes. Zero is an empty cell, never a Sudoku digit. Store rows consecutively in a 16-element array: row r, column c has index (r - 1) * 4 + c. Integer division and remainder translate an index back into its row and column.

Independent Workspace expression - select all, then Print it
| grid index row column |
grid := #(1 2 0 0 0 4 0 2 2 1 0 3 0 0 0 0).
index := (3 - 1) * 4 + 2.
row := (index - 1) // 4 + 1.
column := (index - 1) \\ 4 + 1.
{index. row. column. grid at: index.
 grid count: [:value | value = 0]}

Expected: #(10 3 2 1 9)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Represent a small Sudoku with one flat array
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try row 4, column 3. You should obtain index 15, value 0. The initial grid has nine blanks.

Download this checkpoint

02 - Build peers without including the cell itself

A peer shares a row, column or box. Scan the sixteen possible indices once, selecting each matching index only once. This avoids counting the same peer twice when it shares both a row and a box. Each cell in this 4-by-4 board has seven distinct peers.

Independent Workspace expression - select all, then Print it
| row col box peers |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
{(peers at: 1) asArray.
 peers allSatisfy: [:group | group size = 7].
 (1 to: 16) allSatisfy: [:i | ((peers at: i) includes: i) not] }

Expected: #(#(2 3 4 5 6 9 13) true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Build peers without including the cell itself
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try cell 16: its peers are 4, 8, 11, 12, 13, 14 and 15. The final true verifies that every cell excludes itself from its peer collection.

Download this checkpoint

03 - Subtract used digits to get real candidate sets

For an empty cell, candidates are {1,2,3,4} minus the values already assigned to its peers. Zero contributes nothing to that subtraction. A Set captures membership; convert to a sorted Array only for deterministic display and tests. Candidates are locally legal possibilities, not a promise of a complete solution.

Independent Workspace expression - select all, then Print it
| row col box peers candidates grid |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
candidates := [:candidateGrid :i |
 ((1 to: 4) asSet difference:
  ((peers at: i) collect: [:j | candidateGrid at: j]) asSet)
  asArray sorted asArray].
grid := #(1 2 0 0 0 4 0 2 2 1 0 3 0 0 0 0).
{candidates value: grid value: 3.
 candidates value: grid value: 4.
 candidates value: grid value: 15}

Expected: #(#(3 4) #(4) #(1 2 4))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Subtract used digits to get real candidate sets
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try cell 7; its candidates are #(1 3). Do not run this block on filled cells and interpret the result as their assigned value.

Download this checkpoint

04 - Apply one simultaneous wave of naked singles

A naked single is an empty cell with exactly one candidate. Compute every candidate from the same original grid, then write the forced values into a copy. These waves make the dependency chain visible: newly assigned digits affect the next wave, rather than changing the meaning of the current scan.

Independent Workspace expression - select all, then Print it
| row col box peers candidates grid next singles |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
candidates := [:candidateGrid :i |
 ((1 to: 4) asSet difference:
  ((peers at: i) collect: [:j | candidateGrid at: j]) asSet)
  asArray sorted asArray].
grid := #(1 2 0 0 0 4 0 2 2 1 0 3 0 0 0 0).
next := grid copy.
singles := (1 to: 16) select: [:i |
 (grid at: i) = 0 and: [(candidates value: grid value: i) size = 1]].
singles do: [:i |
 next at: i put: (candidates value: grid value: i) first].
{singles asArray. next. grid = #(1 2 0 0 0 4 0 2 2 1 0 3 0 0 0 0)}

Expected: #(#(4 5 11 14) #(1 2 0 4 3 4 0 2 2 1 4 3 0 3 0 0) true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Apply one simultaneous wave of naked singles
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Four assignments leave five blanks. Run the same idea using next as the new input: another four cells become forced.

Download this checkpoint

05 - Repeat to a fixed point without guessing

The reusable block returns {status. finalGrid. history}. Each productive wave fills at least one blank and never changes a clue, so there are at most sixteen productive waves. Before each wave, reject repeated nonzero peer values and empty candidate sets. After each simultaneous assignment, the next loop checks for conflicts again. Stop when no single remains: a valid full grid is solved, an incomplete one is stuck.

Independent Workspace expression - select all, then Print it
| row col box peers candidates propagate result input |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
candidates := [:candidateGrid :i |
 ((1 to: 4) asSet difference:
  ((peers at: i) collect: [:j | candidateGrid at: j]) asSet)
  asArray sorted asArray].
propagate := [:sourceGrid |
 | working snapshots outcome choices forced invalid following |
 (sourceGrid size = 16 and: [sourceGrid allSatisfy: [:v |
  v isInteger and: [v between: 0 and: 4]]])
  ifFalse: [Error signal: 'Use 16 integers in 0..4'].
 working := sourceGrid asArray copy. snapshots := OrderedCollection with: working copy.
 outcome := #running.
 [outcome = #running] whileTrue: [
  invalid := (1 to: 16) anySatisfy: [:i |
   (working at: i) ~= 0 and: [(peers at: i) anySatisfy: [:j |
    (working at: i) = (working at: j)]]].
  invalid ifTrue: [outcome := #contradiction] ifFalse: [
   choices := (1 to: 16) collect: [:i |
    (working at: i) = 0
     ifTrue: [candidates value: working value: i]
     ifFalse: [#()]].
   ((1 to: 16) anySatisfy: [:i |
    (working at: i) = 0 and: [(choices at: i) isEmpty]])
    ifTrue: [outcome := #contradiction]
    ifFalse: [
     forced := (1 to: 16) select: [:i |
      (working at: i) = 0 and: [(choices at: i) size = 1]].
     forced isEmpty
      ifTrue: [outcome := (working includes: 0)
       ifTrue: [#stuck] ifFalse: [#solved]]
      ifFalse: [
       following := working copy.
       forced do: [:i | following at: i put: (choices at: i) first].
       working := following. snapshots add: working copy]]]].
 {outcome. working. snapshots asArray}].
input := #(1 2 0 0 0 4 0 2 2 1 0 3 0 0 0 0).
result := propagate value: input.
{result first. result second. result third size - 1.
 input = #(1 2 0 0 0 4 0 2 2 1 0 3 0 0 0 0)}

Expected: #(solved #(1 2 3 4 3 4 1 2 2 1 4 3 4 3 2 1) 3 true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Repeat to a fixed point without guessing
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Three productive waves solve this fixture. The fourth snapshot is the solution because history also contains the starting grid. Change a clue only on an input copy.

Download this checkpoint

06 - Separate solved, stuck and contradiction

An empty grid is stuck under naked singles: all candidates are 1..4. It is not a contradiction. A duplicate clue is a contradiction immediately. A different failure is an empty cell whose peers already forbid every digit, even when the assigned clues do not duplicate each other. These statuses describe this propagation procedure, not a complete satisfiability or uniqueness test.

Independent Workspace expression - select all, then Print it
| row col box peers candidates propagate blank duplicate blocked |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
candidates := [:candidateGrid :i |
 ((1 to: 4) asSet difference:
  ((peers at: i) collect: [:j | candidateGrid at: j]) asSet)
  asArray sorted asArray].
propagate := [:sourceGrid |
 | working snapshots outcome choices forced invalid following |
 (sourceGrid size = 16 and: [sourceGrid allSatisfy: [:v |
  v isInteger and: [v between: 0 and: 4]]])
  ifFalse: [Error signal: 'Use 16 integers in 0..4'].
 working := sourceGrid asArray copy. snapshots := OrderedCollection with: working copy.
 outcome := #running.
 [outcome = #running] whileTrue: [
  invalid := (1 to: 16) anySatisfy: [:i |
   (working at: i) ~= 0 and: [(peers at: i) anySatisfy: [:j |
    (working at: i) = (working at: j)]]].
  invalid ifTrue: [outcome := #contradiction] ifFalse: [
   choices := (1 to: 16) collect: [:i |
    (working at: i) = 0
     ifTrue: [candidates value: working value: i]
     ifFalse: [#()]].
   ((1 to: 16) anySatisfy: [:i |
    (working at: i) = 0 and: [(choices at: i) isEmpty]])
    ifTrue: [outcome := #contradiction]
    ifFalse: [
     forced := (1 to: 16) select: [:i |
      (working at: i) = 0 and: [(choices at: i) size = 1]].
     forced isEmpty
      ifTrue: [outcome := (working includes: 0)
       ifTrue: [#stuck] ifFalse: [#solved]]
      ifFalse: [
       following := working copy.
       forced do: [:i | following at: i put: (choices at: i) first].
       working := following. snapshots add: working copy]]]].
 {outcome. working. snapshots asArray}].
blank := Array new: 16 withAll: 0.
duplicate := #(1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0).
blocked := #(0 1 2 3 4 0 0 0 0 0 0 0 0 0 0 0).
{(propagate value: blank) first.
 (propagate value: duplicate) first.
 (propagate value: blocked) first.
 candidates value: blocked value: 1}

Expected: #(stuck contradiction contradiction #())

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Separate solved, stuck and contradiction
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Cell 1 of blocked sees 1, 2 and 3 in its row and 4 in its column/box. Try an incomplete grid with no singles: never label it unsolvable merely because this block stops.

Download this checkpoint

07 - Validate the representation before solving

Malformed data is a programming/input error, separate from a well-formed Sudoku contradiction. The block requires an indexed collection with exactly sixteen integers in 0..4 and copies it into an Array. Here deliberate errors are caught to make the contract printable. A full grid still undergoes peer validation before it can be called solved.

Independent Workspace expression - select all, then Print it
| row col box peers candidates propagate |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
candidates := [:candidateGrid :i |
 ((1 to: 4) asSet difference:
  ((peers at: i) collect: [:j | candidateGrid at: j]) asSet)
  asArray sorted asArray].
propagate := [:sourceGrid |
 | working snapshots outcome choices forced invalid following |
 (sourceGrid size = 16 and: [sourceGrid allSatisfy: [:v |
  v isInteger and: [v between: 0 and: 4]]])
  ifFalse: [Error signal: 'Use 16 integers in 0..4'].
 working := sourceGrid asArray copy. snapshots := OrderedCollection with: working copy.
 outcome := #running.
 [outcome = #running] whileTrue: [
  invalid := (1 to: 16) anySatisfy: [:i |
   (working at: i) ~= 0 and: [(peers at: i) anySatisfy: [:j |
    (working at: i) = (working at: j)]]].
  invalid ifTrue: [outcome := #contradiction] ifFalse: [
   choices := (1 to: 16) collect: [:i |
    (working at: i) = 0
     ifTrue: [candidates value: working value: i]
     ifFalse: [#()]].
   ((1 to: 16) anySatisfy: [:i |
    (working at: i) = 0 and: [(choices at: i) isEmpty]])
    ifTrue: [outcome := #contradiction]
    ifFalse: [
     forced := (1 to: 16) select: [:i |
      (working at: i) = 0 and: [(choices at: i) size = 1]].
     forced isEmpty
      ifTrue: [outcome := (working includes: 0)
       ifTrue: [#stuck] ifFalse: [#solved]]
      ifFalse: [
       following := working copy.
       forced do: [:i | following at: i put: (choices at: i) first].
       working := following. snapshots add: working copy]]]].
 {outcome. working. snapshots asArray}].
{[propagate value: #(1 2 3)] on: Error do: [:e | #rejected].
 [propagate value: (Array new: 16 withAll: 5)]
  on: Error do: [:e | #rejected].
 [propagate value: (Array new: 16 withAll: 1.5)]
  on: Error do: [:e | #rejected].
 (propagate value: (Array new: 16 withAll: 1)) first.
 (propagate value: #(1 2 3 4 3 4 1 2 2 1 4 3 4 3 2 1)) first}

Expected: #(rejected rejected rejected contradiction solved)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Validate the representation before solving
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try -1 or a string in one cell: reject it rather than treating it as empty. Catching all Error exceptions is only for these deliberate test cases, not a general error-recovery policy.

Download this checkpoint

08 - Regress every single-hole position and every conflicting peer pair

Remove each of sixteen digits from a known solution. Each result must recover that exact solution, preserve its input, and be idempotent when run again. Then place the same digit at every unordered peer pair on an otherwise empty grid: all 56 cases must report contradiction. Finally verify that an empty grid remains stuck. These targeted properties complement the mixed-hole, malformed-input and exhausted-candidate fixtures above.

Independent Workspace expression - select all, then Print it
| row col box peers candidates propagate solution input before result ok holes conflicts |
row := [:i | (i - 1) // 4 + 1].
col := [:i | (i - 1) \\ 4 + 1].
box := [:i | (((row value: i) - 1) // 2 * 2)
 + (((col value: i) - 1) // 2) + 1].
peers := (1 to: 16) collect: [:i |
 (1 to: 16) select: [:j | (i ~= j) and: [
  ((row value: i) = (row value: j)) or: [
   ((col value: i) = (col value: j)) or: [
    (box value: i) = (box value: j)]]]]].
candidates := [:candidateGrid :i |
 ((1 to: 4) asSet difference:
  ((peers at: i) collect: [:j | candidateGrid at: j]) asSet)
  asArray sorted asArray].
propagate := [:sourceGrid |
 | working snapshots outcome choices forced invalid following |
 (sourceGrid size = 16 and: [sourceGrid allSatisfy: [:v |
  v isInteger and: [v between: 0 and: 4]]])
  ifFalse: [Error signal: 'Use 16 integers in 0..4'].
 working := sourceGrid asArray copy. snapshots := OrderedCollection with: working copy.
 outcome := #running.
 [outcome = #running] whileTrue: [
  invalid := (1 to: 16) anySatisfy: [:i |
   (working at: i) ~= 0 and: [(peers at: i) anySatisfy: [:j |
    (working at: i) = (working at: j)]]].
  invalid ifTrue: [outcome := #contradiction] ifFalse: [
   choices := (1 to: 16) collect: [:i |
    (working at: i) = 0
     ifTrue: [candidates value: working value: i]
     ifFalse: [#()]].
   ((1 to: 16) anySatisfy: [:i |
    (working at: i) = 0 and: [(choices at: i) isEmpty]])
    ifTrue: [outcome := #contradiction]
    ifFalse: [
     forced := (1 to: 16) select: [:i |
      (working at: i) = 0 and: [(choices at: i) size = 1]].
     forced isEmpty
      ifTrue: [outcome := (working includes: 0)
       ifTrue: [#stuck] ifFalse: [#solved]]
      ifFalse: [
       following := working copy.
       forced do: [:i | following at: i put: (choices at: i) first].
       working := following. snapshots add: working copy]]]].
 {outcome. working. snapshots asArray}].
solution := #(1 2 3 4 3 4 1 2 2 1 4 3 4 3 2 1).
ok := true. holes := 0. conflicts := 0.
1 to: 16 do: [:i |
 input := solution copy. input at: i put: 0. before := input copy.
 result := propagate value: input. holes := holes + 1.
 ok := ok & (result first = #solved) & (result second = solution)
  & (input = before)
  & ((propagate value: result second) second = result second)].
1 to: 16 do: [:i | (peers at: i) do: [:j | i < j ifTrue: [
 input := Array new: 16 withAll: 0.
 input at: i put: 1; at: j put: 1.
 conflicts := conflicts + 1.
 ok := ok & ((propagate value: input) first = #contradiction)]]].
ok := ok & ((propagate value: (Array new: 16 withAll: 0)) first = #stuck).
{ok. holes. conflicts}

Expected: #(true 16 56)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Regress every single-hole position and every conflicting peer pair
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Break the box comparison in peers and rerun the tests; box-only conflicts must still be detected. Add an assertion for the three-wave fixture and its exact history.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Sudoku candidates: propagate constraints without guessing native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

Candidates are locally permitted digits, not proven solution values. A cell with two candidates may have only one globally possible value, or no completion at all. Naked-single propagation does not infer every logical consequence.

A contradiction is either repeated nonzero values in a row, column or box, or an empty cell with no candidate. The block checks duplicates before calling a full grid solved and after every simultaneous wave. Other global contradictions may remain undetected in a stuck board.

Stuck means no naked single exists in an incomplete board. It does not mean unsolvable, unique, or ambiguous. Hidden singles and other deductions can make progress beyond this implementation; backtracking instead branches on assumptions and explores alternatives.

Zero is only a storage marker. Never count it as a clue conflict. Use a Set to deduplicate forbidden digits, exclude the cell itself from its peers, and sort candidates only when presenting or testing them.

Each productive wave strictly reduces the number of blanks. Filled values never change, and their assignments were forced by the previous grid. Copying input and each history entry prevents aliasing from erasing the trace. This teaching version recomputes candidates and retains snapshots rather than optimizing allocation.

To extend to ordinary 9-by-9 Sudoku, use side 9, box width 3, 81 cells and digits 1..9. Replace every bound and use box := ((row - 1) // 3 * 3) + ((col - 1) // 3) + 1. Each cell then has 20 peers. The algorithm still may stop stuck; larger dimensions do not turn propagation into search.

Three practice challenges

Find hidden singles without guessing

A unit may contain several multi-candidate cells but allow one digit in only one place. Describe how to find this hidden single in a row, column or box. What checks are needed when combining these proposals with naked singles?

Show solution

Build all twelve units: four rows, four columns and four boxes. For each missing digit in a unit, select its empty cells whose candidates include that digit. One eligible cell forces the digit there; zero eligible cells proves contradiction. Gather proposals before applying them. Reject conflicting digits proposed for one cell and validate peer conflicts after a wave. Do not call a multi-candidate cell a naked single just because a unit forces its value.

Add a backtracking layer

When propagation returns stuck, sketch a complete search wrapper. How would you distinguish no solutions, one solution, and more than one solution without confusing a successful branch with uniqueness?

Show solution

First propagate a copied grid. Return no solutions on contradiction and one grid on solved. Otherwise choose an empty cell with the fewest candidates, clone the propagated grid for each candidate, assign that assumption and recurse. The finite number of blanks decreases on every branch. Combine solutions from all branches, or stop after finding two when checking uniqueness. One discovered solution proves existence only; uniqueness requires exhausting every other branch. Keep assumptions separate from forced deductions in the trace.

Verify the complete wave history

Extend the mixed-hole fixture test to assert blank counts and preservation of the original clues across every snapshot. What should those counts be, and what invariant would detect an accidental overwrite?

Show solution

For the checkpoint 5 puzzle, history contains four grids with 9, 5, 1 and 0 blanks. Compute counts using result third collect: [:grid | grid count: [:v | v = 0]]. For every original nonzero cell i, assert that every snapshot has (grid at: i) = (input at: i). Also assert that consecutive snapshots never change a previous nonzero value and that every newly filled value was the sole candidate computed from the previous snapshot. This checks the explanation as well as the final answer.

Continue learning

Eight Queens | Collections | Testing

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.