s LearnSqueak.com

SMALLTALK LAB

Floyd cycle detection: find a loop with two moving states

Use a tortoise and hare to detect repetition, locate its entry and measure its period, with nil-safe Smalltalk checkpoints and a computed native state replay.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 and a Workspace. Select one complete checkpoint and choose Print it. Every block is independent. Array indexes are one-based node identifiers, not payloads; each successor must be nil or a valid index. The examples assume this input contract rather than silently treating malformed indexes as termination. Steps 2, 4 and 5 deliberately use a known cyclic fixture; steps 3 and 6 handle nil endings.

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 - Give each state exactly one successor

An Array can describe a functional graph: the value at index i is the next state after i. Here 1 and 2 form a tail, then 3, 4, 5 and 6 repeat. Unlike a general graph traversal, there is never a choice of outgoing edge.

Independent Workspace expression - select all, then Print it
| successors state visited |
successors := #(2 3 4 5 6 3).
state := 1. visited := OrderedCollection new.
9 timesRepeat: [
 visited add: state.
 state := successors at: state].
visited asArray

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

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Give each state exactly one successor
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try starting at 4. The cycle is the same, but there is no tail. A cycle is a property of reachable states, not necessarily every entry in the Array.

Download this checkpoint

02 - Move once and twice before comparing

Floyd’s tortoise moves one successor per round; the hare moves two. Both begin at 1, but that initial equality proves nothing. Compare after movement. Each trace row records round, slow and fast; the first real meeting is at state 5, not at the entry 3.

Independent Workspace expression - select all, then Print it
| successors slow fast rounds trace |
successors := #(2 3 4 5 6 3).
slow := 1. fast := 1. rounds := 0.
trace := OrderedCollection new.
[
 slow := successors at: slow.
 fast := successors at: (successors at: fast).
 rounds := rounds + 1.
 trace add: {rounds. slow. fast}.
 slow = fast] whileFalse.
trace asArray

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

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Move once and twice before comparing
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Verify that after t rounds the pointers are x(t) and x(2t). Once both are in the cycle, their relative position changes by one each round, so they must meet within one cycle length.

Download this checkpoint

03 - Stop safely when a chain ends

nil means no next state, not a real cycle node. The successor block returns nil immediately for nil, so both nested hare calls are safe. The loop only accepts equal non-nil states as a meeting. Unlike step 2, this detector works for terminating chains too.

Independent Workspace expression - select all, then Print it
| meeting |
meeting := [:successors :start | | next slow fast found |
 next := [:state | state isNil
  ifTrue: [nil] ifFalse: [successors at: state]].
 slow := start. fast := start. found := false.
 [fast notNil and: [found not]] whileTrue: [
  slow := next value: slow.
  fast := next value: (next value: fast).
  found := fast notNil and: [slow = fast]].
 found ifTrue: [slow] ifFalse: [nil]].
{meeting value: #(2 3 nil) value: 1.
 meeting value: #(2 nil) value: 1.
 meeting value: #() value: nil.
 meeting value: #(1) value: 1.
 meeting value: #(2 3 4 5 6 3) value: 1}

Expected: #(nil nil nil 1 5)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Stop safely when a chain ends
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The odd-length chain, even-length chain, empty start, self-loop and longer cycle cover different stopping paths. Never interpret nil=nil as evidence of a cycle.

Download this checkpoint

04 - Reset one pointer to find the entry

First find a meeting in this known cyclic fixture. Reset slow to the start, leave fast at the meeting, then move both one step. They meet at the entry after mu steps, where mu is the tail length. If the detection meeting took t rounds, t is a multiple of the cycle length; this makes x(mu) and x(t+mu) the same state.

Independent Workspace expression - select all, then Print it
| successors slow fast tailLength |
successors := #(2 3 4 5 6 3).
slow := 1. fast := 1.
[
 slow := successors at: slow.
 fast := successors at: (successors at: fast).
 slow = fast] whileFalse.
slow := 1. tailLength := 0.
[slow = fast] whileFalse: [
 slow := successors at: slow.
 fast := successors at: fast.
 tailLength := tailLength + 1].
{slow. tailLength}

Expected: #(3 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Reset one pointer to find the entry
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change both initial pointer assignments and the reset to 3. Expect #(3 0): the start is already in the cycle. Resetting to the original start is essential.

Download this checkpoint

05 - Count one complete lap

Once a cycle state is known, keep that anchor fixed. Move a second pointer once, then count successors until it returns to the anchor. Starting the count at one makes a self-loop have length one. This known fixture uses state 3, the entry already derived above.

Independent Workspace expression - select all, then Print it
| successors entry runner cycleLength |
successors := #(2 3 4 5 6 3).
entry := 3.
runner := successors at: entry. cycleLength := 1.
[runner = entry] whileFalse: [
 runner := successors at: runner.
 cycleLength := cycleLength + 1].
cycleLength

Expected: 4

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Count one complete lap
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Use entry := 5 with the same Array: the result is still 4. Every anchor inside one cycle gives its length; an anchor in the tail would never be revisited.

Download this checkpoint

06 - Combine the phases and test the boundaries

The complete analyzer returns #(entry tailLength cycleLength), or nil when no cycle is reachable. A nil-safe successor protects the detection phase. The later phases run only after a non-nil meeting has proved that this orbit reaches a cycle. No collection of visited states is required.

Independent Workspace expression - select all, then Print it
| analyze |
analyze := [:successors :start | | next slow fast found mu length |
 next := [:state | state isNil
  ifTrue: [nil] ifFalse: [successors at: state]].
 slow := start. fast := start. found := false.
 [fast notNil and: [found not]] whileTrue: [
  slow := next value: slow.
  fast := next value: (next value: fast).
  found := fast notNil and: [slow = fast]].
 found ifFalse: [nil] ifTrue: [
  slow := start. mu := 0.
  [slow = fast] whileFalse: [
   slow := next value: slow. fast := next value: fast. mu := mu + 1].
  length := 1. fast := next value: slow.
  [slow = fast] whileFalse: [
   fast := next value: fast. length := length + 1].
  {slow. mu. length}]].
{analyze value: #(2 3 4 5 6 3) value: 1.
 analyze value: #(2 3 1) value: 1.
 analyze value: #(1) value: 1.
 analyze value: #(2 3 nil) value: 1.
 analyze value: #() value: nil.
 analyze value: #(2 nil 3) value: 1}

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

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Combine the phases and test the boundaries
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The final Array contains an unreachable self-loop at index 3. Starting at 1 still terminates. The analyzer answers a question about one start, not whether the entire graph contains any cycle.

Download this checkpoint

07 - Compare states, not repeated payloads

Indexes identify nodes in the successor representation, so numeric = is the correct comparison. Two distinct linked-list nodes can carry equal text without being the same node. For actual node objects compare references with ==, not just their payloads. Here the two fresh Arrays stand in for distinct nodes.

Independent Workspace expression - select all, then Print it
| firstNode secondNode labels successors |
firstNode := Array with: 'same'.
secondNode := Array with: 'same'.
labels := #('same' 'same' 'last').
successors := #(2 3 nil).
{firstNode = secondNode.
 firstNode == secondNode.
 (labels at: 1) = (labels at: 2).
 1 = 2.
 successors at: 3}

Expected: #(true false true false nil)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Compare states, not repeated payloads
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The first two payloads are equal, yet 1->2->3->nil has no cycle. If node classes redefine = by content, use == throughout Floyd’s comparisons for linked structure identity.

Download this checkpoint

08 - Detect a period without storing a graph

The same method works for a deterministic function. For f(x)=(x*x+1) mod 10, starting at zero visits 0, 1, 2, 5, 6, 7, then 0 again. There is no nil here, and every result lies in the finite set 0 through 9. This finite-state guarantee ensures eventual repetition.

Independent Workspace expression - select all, then Print it
| next slow fast mu length |
next := [:state | ((state * state) + 1) \\ 10].
slow := 0. fast := 0.
[
 slow := next value: slow.
 fast := next value: (next value: fast).
 slow = fast] whileFalse.
slow := 0. mu := 0.
[slow = fast] whileFalse: [
 slow := next value: slow. fast := next value: fast. mu := mu + 1].
length := 1. fast := next value: slow.
[slow = fast] whileFalse: [
 fast := next value: fast. length := length + 1].
{slow. mu. length}

Expected: #(0 0 6)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Detect a period without storing a graph
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try start 3 in both initial assignments and the reset: expect #(0 1 6). A function such as x+1 on unbounded integers does not have a finite-state guarantee and this unbounded loop would not stop.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Floyd cycle detection: find a loop with two moving states 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

Compare only after moving in the detection phase. The initial slow=start and fast=start equality is not a discovered cycle. In the entry phase, however, check equality before moving so that a zero-length tail remains zero.

The nil-safe next block is a guard around both hare advances, not a claim that nil is a graph node. A nil meeting means no reachable cycle. Invalid numeric indexes still raise an error and should be validated at a real application boundary.

After t detection rounds, slow=x(t) and fast=x(2t). At a meeting t is divisible by the cycle length. Resetting one pointer and advancing both equally therefore reaches the entry after mu steps. This entry proof depends on the one-step/two-step speed pairing.

For a reachable tail of length mu and cycle of length lambda, Floyd uses O(mu+lambda) successor evaluations and O(1) auxiliary state, assuming constant-cost successor and comparison operations. An acyclic chain of n nodes takes O(n) evaluations. The input Array and teaching trace are separate storage; collecting all trace rows is not constant-space.

Use = for numeric states and indexes. Use == for identity of mutable linked nodes, where equal payloads or structurally equal nodes do not establish a loop. For abstract value states, equality must be compatible with the successor function.

The successor relation must stay deterministic and unchanged during all three phases. Mutating links or using fresh randomness invalidates the proof. Finite total state spaces eventually repeat; arbitrary infinite-state functions need not terminate.

Three practice challenges

Turn the tail into a full cycle

Change only the last successor of #(2 3 4 5 6 3) to 1. Starting at 1, what triple should the complete analyzer return, and why?

Show solution

Use #(2 3 4 5 6 1). The answer is #(1 0 6): the start is the cycle entry, there is no tail, and six advances return to 1. Verify with analyze value: #(2 3 4 5 6 1) value: 1 in checkpoint 6.

Build a visited-state oracle

How could a Dictionary independently verify both lengths for the main fixture? What memory tradeoff does this make?

Show solution

Record the first zero-based step number for each state before following its successor. Stop on nil or a state already present. If state 3 repeats at step 6 and was first recorded at step 2, entry=3, mu=2, lambda=6-2=4. Unlike Floyd, this uses O(mu+lambda) stored entries, but gives a convenient independent test oracle.

Predict a tail into a self-loop

For #(2 3 4 4), starting at 1, predict the detection meeting, entry, tail length and cycle length. Why must the lap counter start at one?

Show solution

The detection rounds are #(2 3), #(3 4), #(4 4), so the meeting and entry are both 4. The result is #(4 3 1). After one advance from 4 the runner is already back at 4; starting the count at zero would incorrectly give a zero-length cycle.

Continue learning

Linked List | State Machines | First Nil

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