-
Christopher Bohn authoredChristopher Bohn authored
2022 Advent of Code Solutions
Day 1
I like the first few days' problems -- they're simple enough that they make great computational thinking examples for my 100-level students. Breaking the problem down into subproblems:
- Keep track of how many calories an elf is carrying
- Detect when we've reach the end of the list of items that elf is carrying
- Convert strings to integers
- Of the elves considered so far, keep track of the number of calories being carried by the elf who is carrying the most calories (or the three elves who are carrying the most calories)
- Update that count when we've finished with an elf
- For part 1, we must determine whether the most-recent elf is carrying more calories than the maximum among the previous elves
- For part 2, we must determine whether the most-recent elf is carrying more calories than any of the previous top-three
- Produce the result
- For part 1, the result is the maximum number of calories being carried by any one elf
- For part 2, the result is the sum of the number of calories being carried by the top three
While I wouldn't expect my students to be able to provide solutions in quite so few lines as I did -- we don't teach the Java streams API in CS1 -- they could definitely do this problem. The only wrinkle is that a blank line isn't the only way to reach the end of an elf's list.
Refactoring opportunity
Parts 1 & 2 differ only in how many "maximum" elves we're tracking and, consequently, how we perform our update. My part 2 solution used a set that can never grow to more than 3 items because we're tracking the top three elves. Part 1 can be thought of as a degenerate case of tracking the top "one" elf; this suggests that it can be solved with a set that can never grow to more than 1 item. Which means we can use the same solution for both parts, parameterized by the top "number" of elves, which becomes the upper limit of the size of the set.
Day 2
(coming soon)