SMALLTALK LAB
Interval scheduling: choose the most compatible jobs
Build an earliest-finish greedy scheduler in native Squeak. Model touching endpoints precisely, trace accepted and rejected jobs, prove the exchange argument and verify optimal counts against exhaustive search.
Before you begin
Use a native Squeak 6.1 Workspace. Select one entire checkpoint and choose Print it. All eight expressions are independent and require no installed classes or packages. Use Do it for the separate Morphic timeline board, setting stage to 0 through 4. Jobs have unique IDs and finite comparable numeric endpoints with start < finish; this lesson schedules one resource with no setup or travel 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 show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.
01 - Model jobs as half-open intervals
A job is #(id start finish), occupying [start, finish). Its start belongs to the interval and its finish does not. The objective is the largest number of whole jobs on one resource, with equal value per job. Selecting jobs preserves individual records; merging intervals instead computes their union. IDs below are unique symbols and endpoints are ordinary, mutually comparable finite numbers.
| jobs durations |
jobs := #(#(A 0 3) #(B 1 4) #(C 3 5)).
durations := jobs collect: [:job | job third - job second].
{durations. (jobs first third = jobs third second)}Expected: #(#(3 3 2) true)

Try it: A finishes at 3 and C begins at 3. Both can be scheduled. Try moving C to start at 2 and explain why the answer changes.
02 - Test compatibility without depending on input order
Two positive-duration jobs are compatible if either one finishes no later than the other starts. This symmetric test works even when jobs arrive in reverse order. Equality permits touching endpoints; using < would incorrectly reject back-to-back work.
| compatible a b c |
compatible := [:left :right |
(left third <= right second) or: [right third <= left second]].
a := #(A 0 3). b := #(B 1 4). c := #(C 3 5).
{compatible value: a value: b.
compatible value: a value: c.
compatible value: c value: a.
compatible value: a value: a}Expected: #(false true true false)

Try it: A positive-duration job conflicts with itself. Try negative endpoints such as [-3, 0) and [0, 2); no special zero boundary is needed.
03 - Sort by earliest finish, with a reproducible tie rule
The greedy priority is finish time, not start time or duration. Equal finish times leave the same future boundary, so any compatible tied job is safe. Sorting tied jobs by their unique ID gives reproducible results, not a better optimum. The sorted: message returns a new collection and leaves the input intact.
| jobs ordered |
jobs := #(#(A 0 3) #(B 1 4) #(C 3 5) #(D 4 7) #(E 5 7) #(F 7 9) #(G 0 9)) reversed.
ordered := jobs sorted: [:a :b |
a third = b third
ifTrue: [a first asString <= b first asString]
ifFalse: [a third < b third]].
{(ordered collect: [:job | job first]) asArray.
(jobs collect: [:job | job first]) asArray}Expected: #(#(A B C D E F G) #(G F E D C B A))

Try it: The input stays G F E D C B A while the result is A B C D E F G. Try a different shuffle; D and E both finish at 7, and F and G both finish at 9.
04 - Scan once and keep the last accepted finish
Start without a boundary, accept the first job, then accept a job only when its start is at least lastFinish. Rejected jobs must not change lastFinish. This trace records the ID, decision and boundary after every candidate. Notice that rejecting D leaves the boundary at 5, allowing E.
| jobs ordered chosen lastFinish trace accept |
jobs := #(#(A 0 3) #(B 1 4) #(C 3 5) #(D 4 7) #(E 5 7) #(F 7 9) #(G 0 9)).
ordered := jobs sorted: [:a :b |
a third = b third
ifTrue: [a first asString <= b first asString]
ifFalse: [a third < b third]].
chosen := OrderedCollection new. trace := OrderedCollection new.
lastFinish := nil.
ordered do: [:job |
accept := lastFinish isNil or: [job second >= lastFinish].
accept ifTrue: [chosen add: job. lastFinish := job third].
trace add: {job first. accept. lastFinish}].
{(chosen collect: [:job | job first]) asArray. trace asArray}Expected: #(#(A C E F) #(#(A true 3) #(B false 3) #(C true 5) #(D false 5) #(E true 7) #(F true 9) #(G false 9)))

Try it: After each acceptance, every chosen pair is compatible and the boundary equals the final chosen finish. Try changing >= to >; it will discard valid touching jobs.
05 - Package the algorithm and justify the greedy choice
Take an optimal schedule ordered by time and call its first job o. The earliest-finishing job g finishes no later than o. Replacing o with g cannot conflict with any later job, since all those jobs start at or after o finishes. Thus some optimum begins with g. Repeat this exchange argument on jobs starting at or after g finishes. Induction proves maximum cardinality, while the scan invariant proves feasibility. The block rejects nonpositive durations and uses nil so negative times remain valid.
| schedule jobs |
schedule := [:inputJobs |
| ordered chosen lastFinish |
inputJobs do: [:job |
job second < job third
ifFalse: [Error signal: 'Each job must have start < finish']].
ordered := inputJobs sorted: [:a :b |
a third = b third
ifTrue: [a first asString <= b first asString]
ifFalse: [a third < b third]].
chosen := OrderedCollection new. lastFinish := nil.
ordered do: [:job |
(lastFinish isNil or: [job second >= lastFinish]) ifTrue: [
chosen add: job. lastFinish := job third]].
chosen asArray].
jobs := #(#(A 0 3) #(B 1 4) #(C 3 5) #(D 4 7) #(E 5 7) #(F 7 9) #(G 0 9)).
{(schedule value: jobs) collect: [:job | job first].
schedule value: #().
(schedule value: #(#(N -5 -2) #(P -2 1)))
collect: [:job | job first]}Expected: #(#(A C E F) #() #(N P))

Try it: Try a shuffled input and confirm the chosen IDs. The proof promises an optimal count, not uniqueness of the chosen schedule.
06 - Check ties and deliberately invalid durations
A zero-length job has special semantics and is excluded by this lesson; a reversed interval is also rejected. Inputs must already have the stated three-field numeric shape. Validation here checks duration, not arbitrary malformed records or NaN. Equal finish times can produce different optimal identities without changing the maximum count.
| schedule |
schedule := [:inputJobs |
| ordered chosen lastFinish |
inputJobs do: [:job |
job second < job third
ifFalse: [Error signal: 'Each job must have start < finish']].
ordered := inputJobs sorted: [:a :b |
a third = b third
ifTrue: [a first asString <= b first asString]
ifFalse: [a third < b third]].
chosen := OrderedCollection new. lastFinish := nil.
ordered do: [:job |
(lastFinish isNil or: [job second >= lastFinish]) ifTrue: [
chosen add: job. lastFinish := job third]].
chosen asArray].
{(schedule value: #(#(Z 0 2) #(A 1 2) #(B 2 3)))
collect: [:job | job first].
[schedule value: #(#(Z 2 2))]
on: Error do: [:error | #rejected].
[schedule value: #(#(R 5 2))]
on: Error do: [:error | #rejected].
(schedule value: #(#(A 0 2) #(B 0 2))) size}Expected: #(#(A B) rejected rejected 1)

Try it: Try renaming A in the tied fixture to Y. A tie-break changes the selected ID, but not the boundary or the optimum count. Error handlers here only make deliberate failures printable.
07 - Break two plausible alternative greedy rules
Earliest start can choose one long job and block several short ones. Shortest duration also fails: a short job can straddle the boundary between two compatible jobs. The bad-policy block below processes jobs by its comparator and accepts only jobs compatible with everything already chosen, so its failure is not an artifact of a chronological-only scan.
| chooseBy earliestStart shortestDuration |
chooseBy := [:jobs :before |
| chosen |
chosen := OrderedCollection new.
(jobs sorted: before) do: [:job |
(chosen allSatisfy: [:other |
(job third <= other second) or: [other third <= job second]])
ifTrue: [chosen add: job]].
(chosen collect: [:job | job first]) asArray].
earliestStart := chooseBy
value: #(#(Long 0 10) #(B 1 2) #(C 2 3) #(D 3 4))
value: [:a :b | a second <= b second].
shortestDuration := chooseBy
value: #(#(A 0 4) #(Bridge 3 5) #(B 4 8))
value: [:a :b | (a third - a second) <= (b third - b second)].
{earliestStart. shortestDuration}Expected: #(#(Long) #(Bridge))

Try it: The optima are B C D (three jobs) and A B (two jobs). Try adding a job at [10, 11); it helps both schedules but does not repair the first rule.
08 - Compare against an exhaustive independent oracle
Generate all ten positive-duration intervals with integer endpoints from 0 through 4. Treat every one of the 1,024 subsets as an input fixture. For each fixture enumerate all its subsets, test every selected pair directly, and take the largest feasible count. This checks the greedy answer against an independent brute-force oracle, including empty input, ties, nesting and touching endpoints. The oracle is intentionally exponential and only suitable for tiny tests.
| schedule universe cases checked ok jobs best candidate valid greedy |
schedule := [:inputJobs |
| ordered chosen lastFinish |
inputJobs do: [:job |
job second < job third
ifFalse: [Error signal: 'Each job must have start < finish']].
ordered := inputJobs sorted: [:a :b |
a third = b third
ifTrue: [a first asString <= b first asString]
ifFalse: [a third < b third]].
chosen := OrderedCollection new. lastFinish := nil.
ordered do: [:job |
(lastFinish isNil or: [job second >= lastFinish]) ifTrue: [
chosen add: job. lastFinish := job third]].
chosen asArray].
universe := OrderedCollection new.
0 to: 3 do: [:start |
start + 1 to: 4 do: [:finish |
universe add: {universe size + 1. start. finish}]].
cases := 1 bitShift: universe size. checked := 0. ok := true.
0 to: cases - 1 do: [:mask |
jobs := OrderedCollection new.
1 to: universe size do: [:i |
(mask bitAnd: (1 bitShift: i - 1)) ~= 0
ifTrue: [jobs add: (universe at: i)]].
best := 0.
0 to: (1 bitShift: jobs size) - 1 do: [:subset |
candidate := OrderedCollection new.
1 to: jobs size do: [:i |
(subset bitAnd: (1 bitShift: i - 1)) ~= 0
ifTrue: [candidate add: (jobs at: i)]].
valid := true.
1 to: candidate size do: [:i |
i + 1 to: candidate size do: [:j |
| a b |
a := candidate at: i. b := candidate at: j.
valid := valid and: [
(a third <= b second) or: [b third <= a second]]]].
valid ifTrue: [best := best max: candidate size]].
greedy := schedule value: jobs.
ok := ok & (greedy size = best). checked := checked + 1].
{ok. universe size. checked}Expected: #(true 10 1024)

Try it: There are 59,049 candidate subsets across all fixtures, including the empty candidate. Try changing >= to > in schedule; the oracle should expose the endpoint bug. Testing supplements, rather than replaces, the exchange proof.
Watch the computed states

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
Use half-open intervals [start, finish): finish = next start is compatible. The reusable block rejects zero and negative durations. It assumes three-field jobs with valid finite numeric endpoints; it is not a general input parser.
This is selection, not merging. Keep original jobs and maximize their count. Merging overlapping ranges computes a union and answers a different question.
Sort by finish time first. Tied finishes can be ordered arbitrarily for optimality; unique-ID tie-breaking only makes the chosen identities reproducible. Not every tied job is compatible with the current prefix.
Update lastFinish only after acceptance. Using nil for the initial boundary admits negative times. Starting at zero silently rejects jobs before time zero.
With constant-cost comparisons, sorting costs O(n log n) and the scan O(n). This non-mutating teaching version uses O(n) auxiliary storage for the sorted copy and output. Already finish-sorted input needs only a linear scan. The exhaustive oracle has exponential cost and is not the production algorithm.
Earliest finish maximizes the number of equal-value jobs on one resource. For weights, deadlines with flexible starts, multiple resources, setup times or travel times, the objective or constraints change. A weighted job [0, 4) worth 100 can beat two jobs [0, 2) and [2, 4) worth 1 each; earliest finish would select value 2.
Three practice challenges
Make the endpoint convention visible
For A [0, 2), B [2, 4), C [1, 3), list a maximum schedule. What changes if both endpoints are closed? Which two comparisons must change in the scheduler and oracle?
Show solution
For half-open intervals choose A then B, count 2. With closed intervals, A and B share time 2, so only one of the three jobs can be selected. Change the scan acceptance from >= to > and both oracle compatibility comparisons from <= to <. State the convention before altering code; the exchange argument still works with the new compatibility rule.
Show that optimal schedules need not be unique
Use A [0, 2), B [1, 2), C [2, 4). Give two maximum schedules. Explain why reversing the tie-break is safe but using earliest start as the primary priority is not.
Show solution
A C and B C both have count 2. A and B finish at the same boundary, so either leaves C available. Reversing the tie-break changes identity only. Earliest start as the primary priority can choose [0, 10) instead of [1, 2), [2, 3), [3, 4), reducing the count from 3 to 1.
Design the weighted version, without reusing the wrong proof
Suppose every job also has a positive value. For A [0, 2) value 1, B [2, 4) value 1, C [0, 4) value 100, compare maximum count and maximum value. Describe a dynamic-programming recurrence after sorting by finish time.
Show solution
Maximum count chooses A and B, count 2 and total value 2. Maximum value chooses C, count 1 and total value 100. For finish-sorted jobs numbered 1..n, let p(j) be the last earlier index whose finish <= start(j), or 0 if none. Set M(0)=0 and M(j)=max(M(j-1), value(j)+M(p(j))). The two alternatives skip or take job j; taking it restricts the prefix to p(j). Binary search finds predecessors in O(n log n) total, followed by O(n) DP and optional reconstruction. The unweighted exchange proof fails because replacement may lose value.
Continue learning
Merging Intervals | Knapsack | Sorting Visualiser
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.