s LearnSqueak.com

SMALLTALK LAB

Stable matching: hold proposals without blocking pairs

Build Gale–Shapley deferred acceptance in Smalltalk, trace replacements, independently check stability, and see why the proposing side changes the outcome.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 and a Workspace. Select each complete expression and choose Print it; no earlier variables or installed classes are required. There are equally many agents and projects, each with capacity one. Every preference row is a strict, complete permutation of 1 through n, and both outer Arrays have n rows. Zero means unassigned, never a valid index. These are abstract fixtures, not a system for making decisions about real people. This lesson assumes the input contract rather than implementing a general preference parser.

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.

01 - Separate names from preference positions

Three fictional agents, Amber, Birch and Cobalt, propose to three abstract projects, X, Y and Z. Each row lists every opposite-side index exactly once, best first. An index identifies an object; its position in a row is its preference rank.

Independent Workspace expression - select all, then Print it
| agents projects offers |
agents := #(Amber Birch Cobalt). projects := #(X Y Z).
offers := #(#(1 2 3) #(1 2 3) #(3 2 1)).
{agents first. (offers first collect: [:i | projects at: i]).
 projects at: (offers third first)}

Expected: #(Amber #(X Y Z) Z)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Separate names from preference positions
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change Cobalt's row to #(2 3 1). The final name becomes Y. Do not repeat or omit a project.

Download this checkpoint

02 - Invert a preference row for constant-time comparisons

Project X ranks Birch first, Amber second and Cobalt third. Build an inverse Array indexed by agent, so a smaller value means a better proposal. Creating a fresh inverse for each row prevents accidental shared mutable rows.

Independent Workspace expression - select all, then Print it
| order rank |
order := #(2 1 3). rank := Array new: order size.
1 to: order size do: [:position |
 rank at: (order at: position) put: position].
{rank. (rank at: 2) < (rank at: 1)}

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

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Invert a preference row for constant-time comparisons
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the order to #(3 1 2). The inverse becomes #(2 3 1), not the original order.

Download this checkpoint

03 - Identify a blocking pair

Stability forbids an unmatched agent/project pair that both prefer each other to their assigned partners. Here the candidate holds Amber at X and Birch at Y. Birch prefers X, and X prefers Birch, so Birch/X blocks that candidate. No numeric utility or total happiness is being optimized.

Independent Workspace expression - select all, then Print it
| offers choices held agent project current bothPrefer |
offers := #(#(1 2) #(1 2)).
choices := #(#(2 1) #(1 2)).
held := #(1 2). agent := 2. project := 1.
current := held indexOf: agent.
bothPrefer := ((offers at: agent) indexOf: project)
 < ((offers at: agent) indexOf: current) and: [
 ((choices at: project) indexOf: agent)
  < ((choices at: project) indexOf: (held at: project))].
bothPrefer

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Identify a blocking pair
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Set agent to 1 and project to 2. Amber prefers the current project, so the answer is false even if only one side wants a change.

Download this checkpoint

04 - Replace a tentative hold, then resume the displaced agent

A project keeps its best proposal so far, not its first proposal forever. When Birch proposes to X, X releases Amber. The proposal pointer for Amber stays at 2: resuming must try the next project rather than repeating the rejected one.

Independent Workspace expression - select all, then Print it
| held next free rank incoming project old |
held := #(1 0 0) copy. next := #(2 2 1) copy.
free := OrderedCollection with: 3.
rank := #(2 1 3). incoming := 2. project := 1.
old := held at: project.
(rank at: incoming) < (rank at: old) ifTrue: [
 held at: project put: incoming. free addLast: old].
{held. free asArray. next at: old}

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

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Replace a tentative hold, then resume the displaced agent
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Amber is now the last free agent and will be processed next. Cobalt is still waiting. A held agent must never also be in free.

Download this checkpoint

05 - Run deferred acceptance to completion

The complete block builds ranks, initializes pointers and repeatedly removes one free agent from a stack. Every proposal advances exactly one pointer. A rejected or displaced agent returns to the stack. The returned Array is indexed by project: #(2 1 3) means X holds Birch, Y holds Amber, Z holds Cobalt.

Independent Workspace expression - select all, then Print it
| match agentPrefs projectPrefs |
match := [:offers :choices | | n ranks next held free a b old |
 n := offers size.
 ranks := choices collect: [:row | | inverse |
  inverse := Array new: n.
  1 to: n do: [:i | inverse at: (row at: i) put: i]. inverse].
 next := Array new: n withAll: 1.
 held := Array new: n withAll: 0.
 free := (1 to: n) reversed asOrderedCollection.
 [free isEmpty] whileFalse: [
  a := free removeLast.
  b := (offers at: a) at: (next at: a).
  next at: a put: (next at: a) + 1.
  old := held at: b.
  (old = 0 or: [((ranks at: b) at: a) < ((ranks at: b) at: old)])
   ifTrue: [held at: b put: a.
    old = 0 ifFalse: [free addLast: old]]
   ifFalse: [free addLast: a]].
 held].
agentPrefs := #(#(1 2 3) #(1 2 3) #(3 2 1)).
projectPrefs := #(#(2 1 3) #(1 2 3) #(3 1 2)).
match value: agentPrefs value: projectPrefs

Expected: #(2 1 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Run deferred acceptance to completion
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Trace four proposals: Amber/X, Birch/X, Amber/Y, Cobalt/Z. The intermediate replacement is tentative; only an empty free stack ends the run.

Download this checkpoint

06 - Test empty, singleton and rejection cases

The empty instance has an empty matching. A single agent and project match immediately. In the last fixture, X rejects Birch because X prefers Amber. Birch must still advance to Y, exercising the rejection branch rather than only the replacement branch.

Independent Workspace expression - select all, then Print it
| match |
match := [:offers :choices | | n ranks next held free a b old |
 n := offers size.
 ranks := choices collect: [:row | | inverse |
  inverse := Array new: n.
  1 to: n do: [:i | inverse at: (row at: i) put: i]. inverse].
 next := Array new: n withAll: 1.
 held := Array new: n withAll: 0.
 free := (1 to: n) reversed asOrderedCollection.
 [free isEmpty] whileFalse: [
  a := free removeLast.
  b := (offers at: a) at: (next at: a).
  next at: a put: (next at: a) + 1.
  old := held at: b.
  (old = 0 or: [((ranks at: b) at: a) < ((ranks at: b) at: old)])
   ifTrue: [held at: b put: a.
    old = 0 ifFalse: [free addLast: old]]
   ifFalse: [free addLast: a]].
 held].
{match value: #() value: #().
 match value: #(#(1)) value: #(#(1)).
 match value: #(#(1 2) #(1 2)) value: #(#(1 2) #(2 1))}

Expected: #(#() #(1) #(1 2))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Test empty, singleton and rejection cases
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Reverse X's ranking in the final fixture. The result becomes #(2 1), exercising displacement instead of immediate rejection.

Download this checkpoint

07 - Audit stability independently of the proposal loop

This oracle accepts only complete permutations and checks every agent/project pair using indexOf: rather than the algorithm's inverse ranks. An empty blocking-pair list certifies stability for this fixture. The second candidate is a valid one-to-one assignment but has the blocking pair Birch/X.

Independent Workspace expression - select all, then Print it
| offers choices blockers |
offers := #(#(1 2 3) #(1 2 3) #(3 2 1)).
choices := #(#(2 1 3) #(1 2 3) #(3 1 2)).
blockers := [:held | | bad |
 ((held asSortedCollection asArray) = #(1 2 3))
  ifFalse: [self error: 'Expected a complete permutation'].
 bad := OrderedCollection new.
 1 to: 3 do: [:a | 1 to: 3 do: [:b |
  (((offers at: a) indexOf: b)
   < ((offers at: a) indexOf: (held indexOf: a)) and: [
   ((choices at: b) indexOf: a)
    < ((choices at: b) indexOf: (held at: b))])
   ifTrue: [bad add: {a. b}]]].
 bad asArray].
{blockers value: #(2 1 3). blockers value: #(1 2 3)}

Expected: #(#() #(#(2 1)))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Audit stability independently of the proposal loop
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try #(1 1 3): the guard rejects it before stability is tested. Checking only the absence of blocking pairs is not a substitute for checking a valid matching.

Download this checkpoint

08 - Swap the proposing side and compare outcomes

This two-by-two instance has two stable matchings. Agents proposing gives each agent its first choice. Projects proposing gives each project its first choice. Normalize both answers to project-indexed arrays before comparing. Under complete strict preferences, deferred acceptance is proposer-optimal among stable matchings, not an optimizer of global welfare.

Independent Workspace expression - select all, then Print it
| match agentPrefs projectPrefs reverse normalized |
match := [:offers :choices | | n ranks next held free a b old |
 n := offers size.
 ranks := choices collect: [:row | | inverse |
  inverse := Array new: n.
  1 to: n do: [:i | inverse at: (row at: i) put: i]. inverse].
 next := Array new: n withAll: 1.
 held := Array new: n withAll: 0.
 free := (1 to: n) reversed asOrderedCollection.
 [free isEmpty] whileFalse: [
  a := free removeLast.
  b := (offers at: a) at: (next at: a).
  next at: a put: (next at: a) + 1.
  old := held at: b.
  (old = 0 or: [((ranks at: b) at: a) < ((ranks at: b) at: old)])
   ifTrue: [held at: b put: a.
    old = 0 ifFalse: [free addLast: old]]
   ifFalse: [free addLast: a]].
 held].
agentPrefs := #(#(1 2) #(2 1)). projectPrefs := #(#(2 1) #(1 2)).
reverse := match value: projectPrefs value: agentPrefs.
normalized := (1 to: 2) collect: [:b | reverse indexOf: b].
{match value: agentPrefs value: projectPrefs. normalized}

Expected: #(#(1 2) #(2 1))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Swap the proposing side and compare outcomes
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: For each result, inspect the two unmatched pairs: one side always prefers its current partner. Both are stable even though the proposing side changes who receives first choices.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Stable matching: hold proposals without blocking pairs 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

Never mutate literal Arrays directly. Mutable state is allocated with Array new:withAll: or copied explicitly. The input preference Arrays remain unchanged. A nested Array must have distinct mutable rows when building inverse ranks.

The invariants are: a project holds at most one agent; an agent is either held once or waiting once; every project keeps the best proposal it has seen; and next points beyond all proposals already tried. Increment next even when a proposal succeeds, because that agent may later be displaced.

Termination follows because no agent repeats a proposal, so at most n squared proposals occur. With equal counts and complete lists, a free agent cannot exhaust all projects: every project would already hold someone, leaving no free agent. This proof fails for incomplete lists, unequal counts, ties or capacities above one; adapt both the model and termination rules before accepting those inputs.

Why the answer is stable: if an agent prefers another project to its final partner, it proposed there earlier and was rejected or displaced. That project only improved its hold afterward, so it prefers its final partner to that agent. The alleged pair cannot both prefer to switch.

Building inverse ranks costs O(n squared) time and space. With Array lookups and amortized stack addLast:/removeLast:, the main loop takes O(n squared) time and O(n) extra state beyond the rank table and inputs. The step 7 oracle uses linear indexOf: lookups inside a pairwise scan, so its generalization is O(n cubed), deliberately simpler but slower.

Stable does not mean maximum total score, unique, or impartial between sides. Rankings are ordinal, not comparable utilities. With strict complete preferences the proposer-optimal stable matching is also receiver-pessimal among stable matchings. Choosing another free-agent processing order changes the trace, but not that proposer-optimal result. No claim here is a fairness guarantee.

Three practice challenges

Make proposal count observable

Modify the complete matcher to return both held and the number of proposals. What count should the three-by-three fixture produce, and what upper bound applies?

Show solution

Add proposals to the block temporaries, initialize it to 0, increment it immediately after choosing b, and replace the final held with {held. proposals}. The fixture returns #(#(2 1 3) 4). Every pair is proposed at most once, so the upper bound is n squared. Count proposals, not successful holds.

Prove two answers are stable

For step 8, list the unmatched pairs for each answer and identify which side refuses to switch. Why does this not contradict proposer optimality?

Show solution

For #(1 2), unmatched pairs are agent 1/project 2 and agent 2/project 1. Both agents already have their first choices. For #(2 1), the unmatched pairs are agent 1/project 1 and agent 2/project 2. Both projects already have their first choices. Each run is optimal for its own proposing side among stable outcomes; neither theorem says all participants get their best choice simultaneously.

Remove one preference carefully

Suppose an agent lists only acceptable projects. Why is simply shortening a row unsafe, and what must change before such data can be supported?

Show solution

The pointer can run past the shortened row, and equal counts no longer guarantee a perfect matching. Track whether each free agent has an untried acceptable project; exhausted agents remain unmatched and are not requeued. Projects also need a way to reject unacceptable agents. Define blocking pairs using mutual acceptability and treat being unmatched as worse than an acceptable partner. Update validation and the stability oracle as well as the loop.

Continue learning

Bipartite Graphs | Stacks Queues | Collections

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