s LearnSqueak.com

RANDOMIZED ALGORITHMS · PERMUTATIONS

Fisher–Yates shuffle: put every item in a random order

Build a copied-array shuffle in Squeak Smalltalk, trace its shrinking choice range, and test every draw history for three items without relying on lucky frequencies.

8 Workspace checkpoints428 exact assertionsNative shrinking-range replay

Before you start

Use a native Squeak 6.1 Workspace. Select one complete checkpoint, including its temporary-variable declaration, and choose Print it. Each block is independent: it includes everything it needs. Do not concatenate all eight blocks into one expression or file in the whole collection. The screenshots show results calculated by the exact displayed expressions.

You will need arrays and collection messages and blocks with arguments. The task is to rearrange every item of a finite list. It is different from reservoir sampling, which retains a subset while a stream arrives, and from the dice lab, which explores observed frequencies.

Download the eight checkpoint expressions, the 428-assertion test expression, or the complete native source kit. No package installation, network access or image changes are required. Opening the optional visual trace creates a window; close it when finished.

01 · Keep the original order safe

A shuffle rearranges all positions; unlike a reservoir sampler, it keeps every item. Start by copying the input container. Each position still refers to the same item, so this is not a deep copy.

Independent Workspace expression · select all, then Print it
| original working |
original := #('red' 'green' 'blue' 'gold').
working := original copy.
working at: 1 put: 'violet'.
{original first. working first}

Check: The original still begins with red. Never use a literal array itself as the mutable working buffer.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Keep the original order safe; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

02 · Exchange two positions without losing either item

Save one old value before overwriting its slot. The three assignments implement a swap. Even when the two indexes are equal, a swap is valid and leaves the array unchanged.

Independent Workspace expression · select all, then Print it
| a saved |
a := #(1 2 3 4) copy.
saved := a at: 4.
a at: 4 put: (a at: 2).
a at: 2 put: saved.
a

Check: The multiset of values is unchanged; only their positions differ.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Exchange two positions without losing either item; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

03 · Freeze the rightmost slot

At boundary i = 4, choose j from 1 through 4, inclusive. Here we script j = 2 to make the lesson reproducible. The item placed at slot 4 is now final. Future draws must not touch it.

Independent Workspace expression · select all, then Print it
| a i j saved active fixed |
a := #(1 2 3 4) copy.
i := a size. j := 2.
saved := a at: i.
a at: i put: (a at: j).
a at: j put: saved.
active := a copyFrom: 1 to: i - 1.
fixed := a at: i.
{active. fixed}

Check: The next choice range is 1..3, not 1..4. The upper endpoint is deliberately allowed.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Freeze the rightmost slot; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

04 · Run the shrinking-range loop

The boundaries are 4, 3 and 2. A scripted chooser returns 2, 1 and 2 in that order. Stop at 2: once all other slots are final, the remaining first item has only one possible home.

Independent Workspace expression · select all, then Print it
| a draws cursor j saved |
a := #(1 2 3 4) copy.
draws := #(2 1 2). cursor := 0.
a size to: 2 by: -1 do: [:i |
 cursor := cursor + 1. j := draws at: cursor.
 saved := a at: i.
 a at: i put: (a at: j).
 a at: j put: saved].
a

Check: The final self-swap at i = 2 is legal. Forcing j to be smaller than i would exclude some permutations.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Run the shrinking-range loop; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

Watch the choice range shrink

NATIVE SQUEAK CAPTURE
Native Squeak Fisher–Yates trace with the original four-item array and no fixed slots
Four genuine Morphic captures replay computed states. Blue is the active prefix; green is the suffix that later swaps leave unchanged. This is a captured-state replay, not mouse footage.

Run the native visual expression as one Do it. Set stage := 0. to 1, 2 or 3 to inspect a later state; close the old window before opening another. Its 1000 × 500-pixel fixed window deliberately displays scripted draws, not a live random experiment. It has no timer, persistence or network access.

The trace stores a copy after every swap. Without that copy, every row could refer to the same mutable array and misleadingly show only the final order. At the last stage the first blue slot is also settled: with only one item left there is no choice to make.

05 · Separate the shuffle from the chooser

A two-argument block accepts the input and a block that chooses an index for each boundary. Validating that result catches a broken chooser immediately. Using a copy means the caller’s order survives even if the chooser later signals an error.

Independent Workspace expression · select all, then Print it
| shuffle |
shuffle := [:input :pick |
 | a j saved |
 a := input asArray copy.
 a size to: 2 by: -1 do: [:i |
  j := pick value: i.
  (j isInteger and: [j between: 1 and: i])
   ifFalse: [Error signal: 'Draw outside 1..i'].
  saved := a at: i.
  a at: i put: (a at: j).
  a at: j put: saved].
 a].
shuffle value: #(1 2 3 4) value: [:upper | upper]

Check: Always returning the upper endpoint gives only self-swaps. The unchanged order is a legitimate shuffle result, not evidence of a bug.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Separate the shuffle from the chooser; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

06 · Handle empty inputs and repeated values

An empty or one-item input makes no chooser calls. Equal values may appear more than once; a correct shuffle preserves their multiplicities. Do not use a Set to check that property because a Set discards duplicates.

Independent Workspace expression · select all, then Print it
| shuffle empty one repeated |
shuffle := [:input :pick |
 | a j saved |
 a := input asArray copy.
 a size to: 2 by: -1 do: [:i |
  j := pick value: i.
  (j isInteger and: [j between: 1 and: i])
   ifFalse: [Error signal: 'Draw outside 1..i'].
  saved := a at: i.
  a at: i put: (a at: j).
  a at: j put: saved].
 a].
empty := shuffle value: #() value: [:upper | Error signal: 'Unexpected draw'].
one := shuffle value: #(7) value: [:upper | Error signal: 'Unexpected draw'].
repeated := shuffle value: #(1 1 2) value: [:upper | 1].
{empty. one. repeated}

Check: All three arrays match the result shown. The empty and singleton cases would fail loudly if the loop called their chooser.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Handle empty inputs and repeated values; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

07 · Plug in one seeded Random object

Squeak’s nextInt: answers from 1 through its positive integer argument. Create one generator per run and keep advancing it; do not restart the same seed on every draw. This check compares two runs with the same seed in this Squeak image, without promising that another version uses the same sequence.

Independent Workspace expression · select all, then Print it
| shuffle first second r1 r2 |
shuffle := [:input :pick |
 | a j saved |
 a := input asArray copy.
 a size to: 2 by: -1 do: [:i |
  j := pick value: i.
  (j isInteger and: [j between: 1 and: i])
   ifFalse: [Error signal: 'Draw outside 1..i'].
  saved := a at: i.
  a at: i put: (a at: j).
  a at: j put: saved].
 a].
r1 := Random seed: 42. r2 := Random seed: 42.
first := shuffle value: #(1 2 3 4 5) value: [:upper | r1 nextInt: upper].
second := shuffle value: #(1 2 3 4 5) value: [:upper | r2 nextInt: upper].
{first = second. first asSortedCollection asArray = #(1 2 3 4 5)}

Check: Both true means reproducible order and preserved membership for this example. Neither claim proves uniform randomness or security.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Plug in one seeded Random object; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

08 · Enumerate every three-item draw history

For three distinct items there are exactly 3 × 2 legal histories. Enumerate them all, rather than hoping repeated random trials look balanced. Each final order should occur once. Arrays used as Dictionary keys are never mutated after insertion.

Independent Workspace expression · select all, then Print it
| shuffle counts |
shuffle := [:input :pick |
 | a j saved |
 a := input asArray copy.
 a size to: 2 by: -1 do: [:i |
  j := pick value: i.
  (j isInteger and: [j between: 1 and: i])
   ifFalse: [Error signal: 'Draw outside 1..i'].
  saved := a at: i.
  a at: i put: (a at: j).
  a at: j put: saved].
 a].
counts := Dictionary new.
1 to: 3 do: [:firstDraw |
 1 to: 2 do: [:secondDraw | | result |
  result := shuffle value: #(1 2 3)
   value: [:upper | upper = 3
    ifTrue: [firstDraw] ifFalse: [secondDraw]].
  counts at: result put: (counts at: result ifAbsent: [0]) + 1]].
{counts size. counts values allSatisfy: [:n | n = 1]}

Check: Six different results, each reached once. This exhaustive finite check tests n = 3; the general fairness argument is still needed.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Enumerate every three-item draw history; evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

Why the algorithm gives every order the same chance

First reason about distinct input positions, even if some positions contain equal values. At boundary i, exactly i unfixed items occupy the prefix. Assuming an independent uniform draw from 1 through i, each of them has probability 1/i of being moved into slot i. That slot is never touched again. The remaining i − 1 items occupy the next active prefix.

For any specified final permutation, the required item for slot n has exactly one possible draw. Then the required item for slot n − 1 has one possible draw among the remaining positions, and so on. Its probability is therefore (1/n) × (1/(n − 1)) × … × (1/2) = 1/n!. There are n! distinct positional permutations, so they all have equal probability. This proof depends on the chooser’s distribution; merely returning an in-range integer is not enough.

The invariant also explains preservation: swapping never creates or removes an item. Empty and singleton inputs have one possible order and require no draws. When values repeat, several positional permutations may look identical, but their multiplicities are still preserved. Our proof is about positions, not a claim that duplicate labels become distinguishable.

Two tempting changes that break the argument

Do not choose from the whole array every time. Consider three passes that each choose one of three positions, independent and uniformly. There are 3³ = 27 equally likely histories but only 3! = 6 possible permutations. Twenty-seven cannot be divided equally into six integer-sized groups, so that procedure cannot give all permutations equal probability. Some outputs must have more histories than others.

Do not exclude the current boundary. Choosing only 1..(i − 1) forbids the item already at i from staying there in that step. The identity permutation is legitimate, as are adjacent repeated values and runs that appear unchanged. The aim is uniform order, not visually dramatic movement. Repeating until the order changes would impose a different distribution and would never terminate for an empty or all-equal input.

Test structure and exact decisions before frequencies

The downloadable test expression contains 428 direct assertions and returns that count when selected as one complete expression and evaluated with Print it. It signals an Error on a mismatch. These are not described as a SUnit suite: the code is an explicit, reproducible assertion harness.

  • Eight assertions evaluate the eight exact published checkpoints.
  • For ten seeds and sizes zero through twelve, 260 assertions check preserved sorted contents and same-seed reproducibility.
  • Every legal three-item and four-item history is enumerated. Thirty permutation checks plus four count checks verify all six or twenty-four results occur exactly once.
  • One hundred twenty small-bound checks exercise the native nextInt: range contract.
  • Six remaining checks reject three invalid chooser values, preserve the caller’s array, count exactly n − 1 chooser calls for four items, and confirm the copy shares contained objects.

Those checks distinguish several contracts that a single sample shuffle would blur together. They do not prove the generator is statistically ideal, that every large permutation is reachable, or that the algorithm is cryptographically secure. The n = 3 and n = 4 enumeration tests are exhaustive for those sizes, not for every size.

Read the actual random-number contract

In this native Squeak 6.1 image, Random seed: 42 creates a seeded generator and nextInt: produces an integer in 1..upper. We verified those sends in the running image and inspected its method source. Open a Browser on Random and search for nextInt: to read it yourself; the current implementation uses integer buckets, bounded rejection attempts and a floating-point fallback. The seed is a reproduction tool, not fresh entropy.

Keep the fairness proof’s ideal assumptions separate from a finite pseudorandom implementation. A fixed seed selects one deterministic sequence. A finite-state generator cannot make arbitrarily many permutations reachable, and a range-conversion implementation needs its own analysis. Do not use this teaching adapter for password generation, adversarial games, lotteries or security-sensitive selection. We make no claim of perfect statistical uniformity from the finite range and seed checks.

The chooser interface makes that boundary explicit. The shuffle owns copying, bounds validation and swaps; the supplied block owns how a number is selected. A failing chooser can have its own side effects, and this wrapper does not undo those effects. It only avoids mutating the input array’s order. It also does not deep-copy objects inside the array.

Count the work and storage honestly

For n ≥ 1 there are n − 1 swaps and chooser calls. Array reads and writes use direct indexes. Under a constant-cost chooser model, the rearrangement work is linear in n; there is no search for a vacant slot and no repeated removal that shifts later entries. The few loop variables occupy constant auxiliary storage, but our caller-friendly implementation allocates a separate n-element result container. Its total extra storage is therefore O(n), not O(1).

The visual trace deliberately keeps n states of an n-element array if generalized to every boundary; that would take O(n²) stored entries. It is a teaching instrument, not the production shuffle. Actual generator costs and large integer bounds are outside the simple operation count. No timing benchmark or speedup is claimed. For measured performance, use the site’s measurement workflow on representative inputs.

Three useful next experiments

  1. Extend the exhaustive history test to five items. Predict the 5! = 120 unique outcomes before running it, and count each final order rather than only checking the number of dictionary keys.
  2. Refactor the two-argument block into a class-side method and move representative assertions into SUnit. Keep the chooser parameter so tests remain independent of a lucky random sequence.
  3. Build a flash-card queue by shuffling references to card objects. Decide whether the next session should repeat the same seed. Explain why editing a card through the shuffled array also affects that same card in the original array.

A shuffled list can be sliced to choose a subset when the complete list is already available. For an unknown-length stream that cannot all be retained, return to reservoir sampling instead of buffering everything just to shuffle it.

Sources and next steps

NIST’s Dictionary of Algorithms and Data Structures: Fisher–Yates shuffle describes the shrinking-range exchange algorithm, linear work and finite-generator limitation. Reviewed 28 October 2026. NIST presents the forward direction; this lesson fixes slots from right to left with the equivalent shrinking prefix. The Smalltalk checkpoints, scripted trace and exact enumeration harness here are original.

The environment reference is the official Squeak documentation; the running Squeak 6.1 image is the authority for the inspected Random messages. Continue with reading Squeak’s own source, observed frequencies, or collection transformations. Keep algorithmic correctness, random-source quality and UI presentation as separate questions.