Fill in

Side Quest: Take It or Leave It

Many puzzles boil down to yes-or-no choices. For each crate: take it, or leave it? Three crates give 2 × 2 × 2 = 8 possible loads.

Recursion can try them all with a three-beat rhythm:

  1. Choose: make a choice (put the crate in chosen).
  2. Explore: recurse to decide the next crate.
  3. Undo: take the choice back, so the next option starts clean.
explore(0)                 chosen = []
├─ take A, explore(1)     chosen = [A]
│  ├─ take B, explore(2)  [A, B]  record
│  └─ skip B, explore(2)  [A]     record
└─ skip A, explore(1)     chosen = []
   ├─ take B, explore(2)  [B]     record
   └─ skip B, explore(2)  []      record

When i reaches the end of the list, every crate has been decided, so the current chosen is one complete answer.

Record a copy!

chosen is one list that keeps changing. Appending chosen itself to results would store the same list again and again, and by the end it is empty. Store a snapshot: chosen.copy().

Pip tip: The undo step is what makes the "skip it" branch work. Without it, the crate you took would still be in the load.

Assignment

Fill each ___ in all_loads(crates) so it returns every possible load:

  1. Record a snapshot of chosen when every crate is decided.
  2. Explore the next crate after taking this one.
  3. Undo the take by removing the last item of chosen.
  4. Explore the next crate again, this time without this crate.

"Take it" comes before "skip it", so all_loads(["A", "B"]) returns [["A", "B"], ["A"], ["B"], []].