
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:
- Choose: make a choice (put the crate in
chosen). - Explore: recurse to decide the next crate.
- 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:
- Record a snapshot of
chosenwhen every crate is decided. - Explore the next crate after taking this one.
- Undo the take by removing the last item of
chosen. - 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"], []].
Fill each ___ in all_loads(crates) so it returns every
possible load:
- Record a snapshot of
chosenwhen every crate is decided. - Explore the next crate after taking this one.
- Undo the take by removing the last item of
chosen. - 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"], []].
Press Run to try your code, then Check to test it.