Recursion Ladder
You'll solve six problems that are miserable with loops and clean with recursion, until you reach for it on purpose.
About
Recursion clicks all at once or not at all, and the way to make it click is volume. Each problem here has a base case and a smaller version of itself. Write the base case first, every single time. When your program crashes with a stack overflow, that isn't failure, it's the base case telling you it's missing.
At a glance
- Per requirement
- 25 XP
- Completion bonus
- 150 XP
- Requirements
- 6
- Takes
- Two weekends
- Skill level
- Intermediate (months of practice)
- Cost
- Free
- Supplies
- Nothing special
- Where
- At home
- Other people
- On your own
Requirements
-
1
Write factorial and Fibonacci recursively, then memoize Fibonacci and time 35 against 400. Plain recursive Fibonacci at 35 takes seconds, while the memoized version at 400 is instant. Use a dictionary cache or your language's decorator. Take a screenshot of both timings. Photo
-
2
List every file in a folder tree recursively, with indentation showing the depth. Directories call the function on themselves. Run it on a real project folder, and skip the .git directory or you'll get a very long screen. Take a screenshot of the tree output. Photo
-
3
Generate every permutation of a five-letter word. You should get 120 results. Then generate every subset of a set of four items, which gives you 16. Both go recursion in and recursion out, with the empty list as the base case. Take a screenshot showing both counts. Photo
-
4
Solve Towers of Hanoi for 6 disks and print each move. That's 63 moves. It's three lines of code if you've got it and thirty if you haven't. Take a screenshot of the move list with the count. Photo
-
5
Flood fill a 20 by 20 grid from one point, like a paint bucket. Draw a grid in text with a few walls. Start at one cell and fill everything connected to it. Then try a 2,000 by 2,000 grid and watch it blow the stack. Fix that with an explicit stack and explain why it works. Take a screenshot of the filled small grid and the fix. Photo
-
6
Walk a nested JSON document of unknown depth and print every path to a leaf. The output looks something like user.address.city: Lisbon. Use a real file, like an API response or a config file. Take a screenshot of the paths. Photo