s LearnSqueak.com

OPTIMIZATION · DYNAMIC PROGRAMMING

0/1 knapsack: choose the most valuable items that fit

Build a capacity-based dynamic program in Squeak Smalltalk, recover the chosen item indexes, make ties and zero-weight items explicit, and verify the answer by exhaustive subset enumeration.

8 standalone checkpoints22,985 native assertions9-state selection replay

Before you start

You have a capacity limit and several indivisible items. Each item may be included once or not at all. Which selection has the greatest total value without exceeding the limit? This is 0/1 knapsack: zero or one copy of each indexed item. It is not fractional packing, unlimited quantities, or a requirement to fill every unit of space.

The edit-distance lesson uses a table to minimize a string-transformation cost. Here the state instead tracks available items and capacity, the objective is a maximum, and the result includes an actual optimal selection reconstructed from the completed table. We will also discover why zero capacity does not necessarily mean zero value.

Open a Workspace in native Squeak 6.1. Each of the eight checkpoints below is a complete, independent expression: copy one block, select the whole block and choose Print it. Nothing needs to be filed in, and there is no hidden setup from an earlier checkpoint. Long checkpoints intentionally repeat their block definitions. Review blocks and collections if value:value:value:, collect: or inject:into: is unfamiliar.

Download all eight checkpoint expressions, the assertion expression, or the complete source kit. Open these as text; do not file in the checkpoint collection or evaluate all eight checkpoints as one expression. The ZIP also includes each checkpoint as a separate file. No network, package, persistent model or animation timer is required.

01 · Describe a bag with item indexes

Keep weights and values in parallel Arrays. An index identifies one available item, even if two items have identical numbers. A proposed selection is feasible when its total weight is at most the capacity; it need not fill the bag exactly.

Independent Workspace expression · select all, then Print it
| weights values chosen weight value |
weights := #(2 3 4 5). values := #(6 10 12 15).
chosen := #(2 3).
weight := chosen inject: 0 into: [:sum :i | sum + (weights at: i)].
value := chosen inject: 0 into: [:sum :i | sum + (values at: i)].
{weight. value. weight <= 7}

Expected Print it result: #(7 22 true)

Check: Items 2 and 3 fit exactly, but we have not yet proved that value 22 is optimal.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Describe a bag with item indexes, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

02 · Catch a tempting greedy shortcut

Highest value per weight first is not an exact 0/1 algorithm. This example deliberately breaks density ties by the smaller item index. After items 2 and 1 are taken, neither remaining item fits, although choosing items 2 and 3 would be better.

Independent Workspace expression · select all, then Print it
| weights values order room chosen total |
weights := #(2 3 4 5). values := #(6 10 12 15).
order := (1 to: weights size) asArray sorted: [:a :b |
 | left right |
 left := (values at: a) * (weights at: b).
 right := (values at: b) * (weights at: a).
 left = right ifTrue: [a < b] ifFalse: [left > right]].
room := 7. chosen := OrderedCollection new. total := 0.
order do: [:i | (weights at: i) <= room ifTrue: [
 chosen add: i. room := room - (weights at: i).
 total := total + (values at: i)]].
{chosen asArray. total. room}

Expected Print it result: #(#(2 1) 16 2)

Check: The ratio comparison is cross multiplication on these positive weights, not division or rounding. This demonstration is not the solver and does not claim to handle every input contract.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Catch a tempting greedy shortcut, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

03 · Give each smaller question its own cell

Let D(i,c) be the greatest value obtainable from the first i items with weight at most c. Reserve row zero for no items and column zero for capacity zero. Squeak stores those mathematical coordinates at row i + 1 and column c + 1.

Independent Workspace expression · select all, then Print it
| table |
table := (1 to: 5) collect: [:i | Array new: 8 withAll: 0].
(table at: 2) at: 3 put: 6.
{table size. table first size.
 (table first at: 3). ((table at: 2) at: 3).
 table first == (table at: 2)}

Expected Print it result: #(5 8 0 6 false)

Check: Each row is freshly allocated. The experiment changes row two without corrupting row one. It is an allocation check, not a completed optimal-value table.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Give each smaller question its own cell, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

04 · Compare taking and skipping each item

Skipping item i keeps D(i−1,c). Taking it adds its value to D(i−1,c−weight), only if it fits. Both choices read the previous row: that is what permits each index at most once. The checked block returns the entire table for inspection.

Independent Workspace expression · select all, then Print it
| tableFor |
tableFor := [:weights :values :capacity |
 | table |
 ((weights isKindOf: Array) and: [values isKindOf: Array])
  ifFalse: [Error signal: 'Use two Arrays'].
 weights size = values size
  ifFalse: [Error signal: 'Weights and values must have equal size'].
 (capacity isInteger and: [capacity >= 0])
  ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
 (weights allSatisfy: [:w | w isInteger and: [w >= 0]])
  ifFalse: [Error signal: 'Weights must be nonnegative integers'].
 (values allSatisfy: [:v | v isInteger and: [v >= 0]])
  ifFalse: [Error signal: 'Values must be nonnegative integers'].
 ((weights size + 1) * (capacity + 1)) > 1000000
  ifTrue: [Error signal: 'Teaching limit: one million table entries'].
 table := (1 to: weights size + 1) collect: [:i |
  Array new: capacity + 1 withAll: 0].
 1 to: weights size do: [:i |
  | previous current weight value |
  previous := table at: i. current := table at: i + 1.
  weight := weights at: i. value := values at: i.
  0 to: capacity do: [:room |
   | best |
   best := previous at: room + 1.
   weight <= room ifTrue: [
    best := best max: (value + (previous at: room - weight + 1))].
   current at: room + 1 put: best]].
 table].
(tableFor value: #(2 3 4 5) value: #(6 10 12 15) value: 7) last

Expected Print it result: #(0 0 6 10 12 16 18 22)

Check: The last row answers all capacities from 0 through 7. Index eight stores capacity seven, not capacity eight.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Compare taking and skipping each item, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

previous is mathematical row i−1, stored at Squeak position i. current is row i, stored at position i+1. The capacity loop includes zero. At each cell, initialize best with the skip option, then compare the take option if the item fits. Reading the current row for that take option would let the same item feed its own later choices and would no longer implement this 0/1 recurrence.

The first row is all zero because no items can contribute value. Do not initialize the entire first column as a permanent boundary: positive-value zero-weight items can improve it. Each call allocates a fresh table, and neither input Array is modified.

05 · Recover the items, not just the score

Walk upward from the final cell. If the value is strictly better than the cell above, the current item was necessary for this chosen optimal path: record its index and subtract its weight. Otherwise skip it. The result contains best value, ascending selected indexes, and the table.

Independent Workspace expression · select all, then Print it
| tableFor solve answer |
tableFor := [:weights :values :capacity |
 | table |
 ((weights isKindOf: Array) and: [values isKindOf: Array])
  ifFalse: [Error signal: 'Use two Arrays'].
 weights size = values size
  ifFalse: [Error signal: 'Weights and values must have equal size'].
 (capacity isInteger and: [capacity >= 0])
  ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
 (weights allSatisfy: [:w | w isInteger and: [w >= 0]])
  ifFalse: [Error signal: 'Weights must be nonnegative integers'].
 (values allSatisfy: [:v | v isInteger and: [v >= 0]])
  ifFalse: [Error signal: 'Values must be nonnegative integers'].
 ((weights size + 1) * (capacity + 1)) > 1000000
  ifTrue: [Error signal: 'Teaching limit: one million table entries'].
 table := (1 to: weights size + 1) collect: [:i |
  Array new: capacity + 1 withAll: 0].
 1 to: weights size do: [:i |
  | previous current weight value |
  previous := table at: i. current := table at: i + 1.
  weight := weights at: i. value := values at: i.
  0 to: capacity do: [:room |
   | best |
   best := previous at: room + 1.
   weight <= room ifTrue: [
    best := best max: (value + (previous at: room - weight + 1))].
   current at: room + 1 put: best]].
 table].
solve := [:weights :values :capacity |
 | table chosen room |
 table := tableFor value: weights value: values value: capacity.
 chosen := OrderedCollection new. room := capacity.
 weights size to: 1 by: -1 do: [:i |
  ((table at: i + 1) at: room + 1) > ((table at: i) at: room + 1)
   ifTrue: [chosen addFirst: i. room := room - (weights at: i)]].
 {table last last. chosen asArray. table}].
answer := solve value: #(2 3 4 5) value: #(6 10 12 15) value: 7.
{answer first. answer second}

Expected Print it result: #(22 #(2 3))

Check: Backtracking skips item 4, takes 3, takes 2, then skips 1. addFirst: restores input order while we traverse indexes downward.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Recover the items, not just the score, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

The three result fields are {bestValue. chosenIndexes. table}. Returning indexes preserves the identity of duplicate items and lets the caller look up names or other metadata in a separate Array. The table and index Array are ordinary mutable objects owned by this result. Mutating a returned table can invalidate later interpretation of that result, but does not alter a separately computed answer.

Watch values become a selected bag

NATIVE SQUEAK CAPTURE
Native Squeak knapsack table with the no-items row revealed and capacities zero through seven
Nine genuine native Morphic captures replay a computed table and its computed backtracking states. This is a captured-state replay, not mouse footage or a performance measurement.

The first five states reveal the item-prefix rows of the completed table. Green highlights the newly revealed row; question marks hide later rows. At the full table, blue marks D(4,7)=22. The remaining four states follow reconstruction: skip 4 → take 3 → take 2 → skip 1. Amber cells mark earlier visited states and blue marks the current state. The selected indexes finish as #(2 3).

For item 4 at capacity 7, skipping already gives 22; taking it gives 15+6=21, so skip. At item 3, taking gives 12+D(2,3)=22, better than skipping at 16. Reduce the remaining capacity to 3, then take item 2 for value 10. Capacity is now zero, but the item loop still checks item 1. The algorithm, not a prewritten list, computes the decisions and selected indexes displayed in the replay.

Download the native visual expression, open it as text and Do it as one whole expression. Set stage := 0. to an integer from 0 through 8 to reproduce a state, closing the previous window first. This is a fixed 1100 × 700 drawing; use a display large enough to see it. The rendering computes the complete table and trace before revealing a state; it is not an instrumented execution timer.

06 · Make equal-value decisions predictable

A tie means the previous row already reaches the same value, so reconstruction skips the later item. This is not a minimum-weight or minimum-item-count policy. It makes the answer deterministic for a given input order; reordering equivalent items changes their identities.

Independent Workspace expression · select all, then Print it
| tableFor solve answer |
tableFor := [:weights :values :capacity |
 | table |
 ((weights isKindOf: Array) and: [values isKindOf: Array])
  ifFalse: [Error signal: 'Use two Arrays'].
 weights size = values size
  ifFalse: [Error signal: 'Weights and values must have equal size'].
 (capacity isInteger and: [capacity >= 0])
  ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
 (weights allSatisfy: [:w | w isInteger and: [w >= 0]])
  ifFalse: [Error signal: 'Weights must be nonnegative integers'].
 (values allSatisfy: [:v | v isInteger and: [v >= 0]])
  ifFalse: [Error signal: 'Values must be nonnegative integers'].
 ((weights size + 1) * (capacity + 1)) > 1000000
  ifTrue: [Error signal: 'Teaching limit: one million table entries'].
 table := (1 to: weights size + 1) collect: [:i |
  Array new: capacity + 1 withAll: 0].
 1 to: weights size do: [:i |
  | previous current weight value |
  previous := table at: i. current := table at: i + 1.
  weight := weights at: i. value := values at: i.
  0 to: capacity do: [:room |
   | best |
   best := previous at: room + 1.
   weight <= room ifTrue: [
    best := best max: (value + (previous at: room - weight + 1))].
   current at: room + 1 put: best]].
 table].
solve := [:weights :values :capacity |
 | table chosen room |
 table := tableFor value: weights value: values value: capacity.
 chosen := OrderedCollection new. room := capacity.
 weights size to: 1 by: -1 do: [:i |
  ((table at: i + 1) at: room + 1) > ((table at: i) at: room + 1)
   ifTrue: [chosen addFirst: i. room := room - (weights at: i)]].
 {table last last. chosen asArray. table}].
answer := solve value: #(2 2) value: #(5 5) value: 2.
{answer first. answer second}

Expected Print it result: #(5 #(1))

Check: The strict > comparison, rather than >=, preserves the earlier item on this tie. Duplicate items remain separate available indexes.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Make equal-value decisions predictable, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

07 · Handle zero capacity without losing free items

Zero weight is allowed, but each item still exists only once. A positive-value free item improves even capacity zero. A zero-value free item ties and is skipped. Therefore fill column zero in every item row, and backtrack through every item even after the remaining capacity becomes zero.

Independent Workspace expression · select all, then Print it
| tableFor solve free empty |
tableFor := [:weights :values :capacity |
 | table |
 ((weights isKindOf: Array) and: [values isKindOf: Array])
  ifFalse: [Error signal: 'Use two Arrays'].
 weights size = values size
  ifFalse: [Error signal: 'Weights and values must have equal size'].
 (capacity isInteger and: [capacity >= 0])
  ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
 (weights allSatisfy: [:w | w isInteger and: [w >= 0]])
  ifFalse: [Error signal: 'Weights must be nonnegative integers'].
 (values allSatisfy: [:v | v isInteger and: [v >= 0]])
  ifFalse: [Error signal: 'Values must be nonnegative integers'].
 ((weights size + 1) * (capacity + 1)) > 1000000
  ifTrue: [Error signal: 'Teaching limit: one million table entries'].
 table := (1 to: weights size + 1) collect: [:i |
  Array new: capacity + 1 withAll: 0].
 1 to: weights size do: [:i |
  | previous current weight value |
  previous := table at: i. current := table at: i + 1.
  weight := weights at: i. value := values at: i.
  0 to: capacity do: [:room |
   | best |
   best := previous at: room + 1.
   weight <= room ifTrue: [
    best := best max: (value + (previous at: room - weight + 1))].
   current at: room + 1 put: best]].
 table].
solve := [:weights :values :capacity |
 | table chosen room |
 table := tableFor value: weights value: values value: capacity.
 chosen := OrderedCollection new. room := capacity.
 weights size to: 1 by: -1 do: [:i |
  ((table at: i + 1) at: room + 1) > ((table at: i) at: room + 1)
   ifTrue: [chosen addFirst: i. room := room - (weights at: i)]].
 {table last last. chosen asArray. table}].
free := solve value: #(0 0 2) value: #(4 0 7) value: 0.
empty := solve value: #() value: #() value: 0.
{free first. free second. empty first. empty second}

Expected Print it result: #(4 #(1) 0 #())

Check: Do not replace the item-count loop with [room > 0]. That would incorrectly drop free items at zero remaining capacity.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Handle zero capacity without losing free items, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

08 · Reject inputs before allocating a table

This teaching API accepts two equally sized Arrays of nonnegative integers and a nonnegative integer capacity. It rejects fractional weights rather than silently rounding them. A separate one-million-entry ceiling prevents accidental enormous tables; that ceiling is a resource policy, not a mathematical restriction.

Independent Workspace expression · select all, then Print it
| tableFor rejected |
tableFor := [:weights :values :capacity |
 | table |
 ((weights isKindOf: Array) and: [values isKindOf: Array])
  ifFalse: [Error signal: 'Use two Arrays'].
 weights size = values size
  ifFalse: [Error signal: 'Weights and values must have equal size'].
 (capacity isInteger and: [capacity >= 0])
  ifFalse: [Error signal: 'Capacity must be a nonnegative integer'].
 (weights allSatisfy: [:w | w isInteger and: [w >= 0]])
  ifFalse: [Error signal: 'Weights must be nonnegative integers'].
 (values allSatisfy: [:v | v isInteger and: [v >= 0]])
  ifFalse: [Error signal: 'Values must be nonnegative integers'].
 ((weights size + 1) * (capacity + 1)) > 1000000
  ifTrue: [Error signal: 'Teaching limit: one million table entries'].
 table := (1 to: weights size + 1) collect: [:i |
  Array new: capacity + 1 withAll: 0].
 1 to: weights size do: [:i |
  | previous current weight value |
  previous := table at: i. current := table at: i + 1.
  weight := weights at: i. value := values at: i.
  0 to: capacity do: [:room |
   | best |
   best := previous at: room + 1.
   weight <= room ifTrue: [
    best := best max: (value + (previous at: room - weight + 1))].
   current at: room + 1 put: best]].
 table].
rejected := [:weights :values :capacity |
 [tableFor value: weights value: values value: capacity. false]
  on: Error do: [:error | true]].
{rejected value: #(1 2) value: #(5) value: 3.
 rejected value: #(1.5) value: #(5) value: 3.
 rejected value: #(1) value: #(5) value: -1.
 rejected value: #() value: #() value: 1000000}

Expected Print it result: #(true true true true)

Check: Catching Error makes rejection visible for the experiment. In an application, show the actual message rather than treating every exception as an ordinary infeasible bag.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Reject inputs before allocating a table, with the evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The highlighted result was evaluated from the displayed complete expression.

State precisely what the solver promises

Inputs: two equally sized Arrays, containing nonnegative integer weights and nonnegative integer values, plus a nonnegative integer capacity. Each position describes a distinct item available once. Zero weights, zero values, duplicate items, overweight items and an empty inventory are valid. A weight larger than the capacity is simply never taken. The empty selection is always feasible.

Output: an exact maximum value, an ascending Array of distinct input indexes that achieves it, and the full capacity table. Unused capacity is allowed. Equal optimal values are resolved by skipping the later item while tracing backward. Equivalently, among tied selections, omit the highest differing index. This is not a promise to minimize total weight or item count, nor to choose the lexicographically smallest displayed index list.

Rejected: non-Array containers, unequal sizes, negative or noninteger weights or values, negative or noninteger capacity, and a table requiring more than 1,000,000 entries. A Float such as 2.0 is rejected even when numerically integral; there is no implicit coercion. The size ceiling is a deliberately simple teaching guard, not a guarantee of responsiveness. Validation scans the supplied arrays first, and very large input collections or huge integer values can still be expensive. Keep experiments modest.

Explain why every choice is safe

After item row i has been filled, every D(i,c) equals the greatest value attainable from a subset of the first i items weighing at most c. For i=0 the only subset is empty, so zero is correct at every capacity. Now assume the previous row is correct. Any feasible subset either omits item i or includes it. Omission is covered by D(i−1,c). Inclusion, when its weight fits, leaves a subset of earlier items at capacity c−weight, giving value+D(i−1,c−weight). These two cases exhaust the possibilities; taking their maximum preserves the invariant.

Only the previous row is read, so a zero-weight item is still used at most once: its contribution comes from a row that does not yet contain it. Each row is a separate Array, so writing the current row cannot corrupt its dependencies. There are finitely many item rows and capacities, which establishes termination.

During reconstruction, maintain a second invariant: value of items already chosen + D(i,remainingCapacity) = original optimum. If the current cell equals the one above, skipping preserves it. If the current cell is greater, the take alternative must achieve it; recording that item and subtracting its weight preserves the same total. The item index decreases on every step, including zero-weight takes. At row zero the remaining value is zero, so the recovered items attain the optimum and fit the original capacity.

The table proof establishes the optimum; the reconstruction proof establishes a witness for it. A correct maximum with a repeated index or an overweight selection would not satisfy the whole API.

Compare against every small subset

Open the complete assertion expression as text, select it all and Print it. The expected result is 22985. A failed assertion signals an Error rather than reaching that number. These are direct assertions executed by native Squeak, not 22,985 separate SUnit methods.

The test first runs all eight exact published checkpoints. It then enumerates every inventory of length 0 through 3 whose weights and values are independently 0, 1 or 2, at every capacity from 0 through 6: (1+9+81+729)×7 = 5,740 problems. For each problem an independent oracle enumerates all subsets using integer membership bits, sums their weights and values, and selects the best feasible subset. Across the grid it examines 43,225 subsets; it does not call the dynamic-programming recurrence.

Four assertions per problem check maximum value, the exact tie-resolved index Array, capacity feasibility, and the value obtained by summing the selected items. The oracle visits masks in ascending order and keeps the first maximum, matching the solver’s omit-the-highest-differing-index rule. Thus the witness comparison also checks uniqueness and order, not just the numeric score.

Ten additional assertions cover every rejection category. Seven focused assertions cover unchanged input arrays, repeated-call equality, distinct row storage, independent returned tables, an exact result involving values of 1050, its chosen indexes, and the exhaustive problem count. Total: 8 + 4×5740 + 10 + 7 = 22985. A finite grid is strong evidence for these cases, not a proof for arbitrary inputs; the invariants explain the general case.

Native verification used Squeak 6.1 build 23976 on 29 October 2026 in a disposable image copy that exited without saving. The kit includes the observed verification report and SHA-256 digests of every tested Smalltalk source file. The downloaded source is the same source used for the checkpoints, tests and native visual captures.

Measure capacity, not just the number of items

With n items and capacity C, the fill performs n×(C+1) cell updates and allocates (n+1)×(C+1) value entries. Counting initialization and boundary cases, table time and storage are O((n+1)(C+1)); the usual nonempty shorthand is O(nC). Reconstruction visits n items and uses up to n selected indexes. Arithmetic on bounded machine-sized integers is treated as constant cost in that shorthand. Squeak’s large integers remain exact, but additions and comparisons on very large values cost more.

This is pseudopolynomial in the numeric capacity, not polynomial in the number of bits used to write that capacity. Doubling C roughly doubles the width; adding one bit can nearly double C. Expressing an unchanged budget in finer units can therefore make this table much larger. Rejecting fractional weights does not justify casually rounding them: rounding changes which selections fit. Scaling exact units changes the capacity and must respect the resource ceiling.

If only the best score is needed, two separate rows reduce table storage to O(C), but discard the history used by this reconstruction. A single-row 0/1 version normally scans capacity downward so a positive-weight item does not reuse its own update. That is a different implementation to derive and test, especially with zero-weight items. Do not simply delete rows while claiming the current item-recovery feature still works.

No speedup or timing measurement is claimed. Use the measurement lesson before comparing implementations, keep the same contracts, and avoid running huge allocations in the interactive UI.

Experiments that sharpen the specification

  1. Use weights #(0 0 2), values #(4 3 7) and capacity zero. Predict both the score and indexes, then run a fresh complete solver expression. Why must two positive-value free items both appear?
  2. Create two equal-valued optimal selections with different total weights. Show that skipping a later item is not a minimum-weight policy. Then design a separate pair-valued objective that compares value first and weight second; update the oracle too.
  3. Make a small case where the bag is optimally left partly empty. Explain why this API is an “at most” problem rather than an “exact weight” problem. An exact-weight variant needs an explicit unreachable state, not an all-zero first row.
  4. Add an Array of item names and translate the chosen indexes into names after solving. Keep indexes in the result so two items with the same name remain distinguishable.
  5. Extract tableFor and solve into class-side methods, then convert the finite checks into SUnit tests. Keep the independent subset oracle test-only: its exponential enumeration is intentionally suitable only for tiny inventories.

When debugging, inspect a single cell and both alternatives before changing the loop. Typical defects are a missing +1 array offset, accidentally reading the current row, aliasing mutable rows, stopping reconstruction at capacity zero, or using >= without revisiting the promised tie rule.

Sources and next steps

MIT OpenCourseWare, 6.006 Recitation 21 notes: The Knapsack Problem (PDF), especially pages 1–5, describes item/capacity state, include-or-skip choices and pseudopolynomial cost. Reviewed 29 October 2026. Those notes index suffixes of the item list; this lesson uses prefixes so the first row naturally represents no items. The Smalltalk implementation, input and tie contracts, zero-weight examples, test grid, reconstruction narrative and native visualization here are original.

Continue with integer bitsets to understand the subset oracle’s membership representation, or return to edit distance and design a reconstructed edit script with its own tie policy. Both exercises ask the same useful follow-up question: after computing an optimal number, can you return a concrete result that proves it?