s LearnSqueak.com

SMALLTALK LAB

Rank and unrank permutations in Squeak

Find an ordering’s position without generating all the orderings before it.

6 tested checkpointsNative Squeak screenshotsNative evaluation replay

Before you begin

Open a Workspace in native Squeak and use Print it on one complete checkpoint at a time.

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 display equivalent Smalltalk literals with different spaces or delimiters.

01 - Count smaller unused choices

In the first slot, choosing 3 skips the two prefix groups that begin with 1 and 2. Remove 3 from the available list, and only unused choices count from now on.

Independent Workspace expression - select all, then Print it
| left index |
left := (1 to: 4) asOrderedCollection.
index := left indexOf: 3.
left removeAt: index.
{index - 1. left asArray}

Expected: {2. #(1 2 4)}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Count smaller unused choices
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: If the first number were 2 instead, the digit would be 1.

Download this checkpoint

02 - Find the first ordering

The sorted sequence always chooses the first unused number, so every digit is zero. The first rank is zero, not one.

Independent Workspace expression - select all, then Print it
| rank |
rank := [:perm |
 | left answer index |
 left := (1 to: perm size) asOrderedCollection.
 answer := 0.
 perm do: [:item |
  index := left indexOf: item.
  index = 0 ifTrue: [Error signal: 'Not a permutation of 1..n'].
  answer := answer * left size + index - 1.
  left removeAt: index].
 answer].
rank value: #(1 2 3)

Expected: 0

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Find the first ordering
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try an empty permutation: there is one empty ordering at rank zero.

Download this checkpoint

03 - Fold the slot choices into the rank

The successive zero-based choice digits are 2, 0, 1, 0. The multipliers shrink with the unused list; read another way, their factorial weights yield 2×3! + 0×2! + 1×1! + 0×0! = 13.

Independent Workspace expression - select all, then Print it
| rank |
rank := [:perm |
 | left answer index |
 left := (1 to: perm size) asOrderedCollection.
 answer := 0.
 perm do: [:item |
  index := left indexOf: item.
  index = 0 ifTrue: [Error signal: 'Not a permutation of 1..n'].
  answer := answer * left size + index - 1.
  left removeAt: index].
 answer].
rank value: #(3 1 4 2)

Expected: 13

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Fold the slot choices into the rank
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: The place at which you choose 4 from #(2 4) contributes one to the rank.

Download this checkpoint

04 - Reverse the calculation by skipping blocks

The first block size is 3! = 6. Rank 13 skips two complete blocks, chooses 3, and leaves one to resolve among permutations of the other numbers.

Independent Workspace expression - select all, then Print it
| unrank |
unrank := [:n :position |
 | left remain result stride index |
 n < 0 ifTrue: [Error signal: 'Negative length'].
 (position < 0 or: [position >= n factorial])
  ifTrue: [Error signal: 'Rank out of range'].
 left := (1 to: n) asOrderedCollection.
 remain := position. result := OrderedCollection new.
 [left isEmpty] whileFalse: [
  stride := (left size - 1) factorial.
  index := (remain // stride) + 1.
  remain := remain - ((index - 1) * stride).
  result addLast: (left at: index).
  left removeAt: index].
 result asArray].
unrank value: 4 value: 13

Expected: #(3 1 4 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Reverse the calculation by skipping blocks
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: After choosing 3, the next block size is 2, so remaining position 1 chooses the first unused number.

Download this checkpoint

05 - Locate the final three-number ordering

Three items give six orderings. At rank 5, the division chooses the last viable number at each slot, giving descending order.

Independent Workspace expression - select all, then Print it
| unrank |
unrank := [:n :position |
 | left remain result stride index |
 n < 0 ifTrue: [Error signal: 'Negative length'].
 (position < 0 or: [position >= n factorial])
  ifTrue: [Error signal: 'Rank out of range'].
 left := (1 to: n) asOrderedCollection.
 remain := position. result := OrderedCollection new.
 [left isEmpty] whileFalse: [
  stride := (left size - 1) factorial.
  index := (remain // stride) + 1.
  remain := remain - ((index - 1) * stride).
  result addLast: (left at: index).
  left removeAt: index].
 result asArray].
unrank value: 3 value: 5

Expected: #(3 2 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Locate the final three-number ordering
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Change the rank to 0 and expect the ascending ordering.

Download this checkpoint

06 - Round-trip every three-number rank

Generate an ordering for each valid position and recover its original rank. This checks all six cases of length three without asserting that a small test is a proof.

Independent Workspace expression - select all, then Print it
| rank unrank |
rank := [:perm |
 | left answer index |
 left := (1 to: perm size) asOrderedCollection.
 answer := 0.
 perm do: [:item |
  index := left indexOf: item.
  index = 0 ifTrue: [Error signal: 'Not a permutation of 1..n'].
  answer := answer * left size + index - 1.
  left removeAt: index].
 answer].
unrank := [:n :position |
 | left remain result stride index |
 n < 0 ifTrue: [Error signal: 'Negative length'].
 (position < 0 or: [position >= n factorial])
  ifTrue: [Error signal: 'Rank out of range'].
 left := (1 to: n) asOrderedCollection.
 remain := position. result := OrderedCollection new.
 [left isEmpty] whileFalse: [
  stride := (left size - 1) factorial.
  index := (remain // stride) + 1.
  remain := remain - ((index - 1) * stride).
  result addLast: (left at: index).
  left removeAt: index].
 result asArray].
((0 to: 5) collect: [:i | rank value: (unrank value: 3 value: i)]) asArray

Expected: #(0 1 2 3 4 5)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Round-trip every three-number rank
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Repeat for length four and positions 0 through 23.

Download this checkpoint

Replay the checkpoints

NATIVE SQUEAK CAPTURE
Rank and unrank permutations in Squeak native Workspace replay
Replay of successive native Squeak Workspace evaluations, not an interaction recording. The static checkpoints appear above.

Reason about correctness and limits

Inputs to rank must contain each integer 1 through n once. To unrank, pass nonnegative integer n and integer position in [0, n factorial).

The ranking is lexicographic and zero-based. It is a position in a sorted list; Kendall distance is a disagreement measure between two orderings.

Searching and removing from the remaining list take quadratic work overall with this representation. Large factorials and repeated factorial computation also add cost.

Three practice challenges

Rank the last ordering

What is the rank of #(3 2 1)?

Show solution

5, because the lexicographically last ordering has rank 3!−1.

Check the first choice

Which number leads the length-four ordering at rank 7?

Show solution

2. The first six begin with 1, and the next six with 2.

Think in blocks

Why does a candidate prefix represent (n−1)! completions?

Show solution

Once its first number is chosen, all possible arrangements of the remaining n−1 distinct numbers are allowed.

Reference

Berger and colleagues: Lehmer code and its historical reference

Continue learning

Kendall Rank Distance | First Sorted

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