AoC 2022 D14: Regolith Reservoir
| Problem statement | Source code | Tags: Physics
← Previous Back to AoC Index Next →
Part 1
I build the literal grid as a Map (Int, Int) Char (exactly same representation as the problem statement). Then I drop sand. Each time, I check if the sand can move down, then down-left, then down-right. If it can't move (same position after moving down), I add it to the grid. It also stops when the sand falls to maxY, to prevent the sand actually falling indefinitely into the abyss.
Now I can drop an indefinite number of sands using iterate. Thanks to laziness, I don't even have to define a stopping condition here. It returns an infinite list of the positions of the dropped sands, and I can just take as many as I need.
In part 1, I need the number of sands before a sand falls into the abyss, i.e., its y position reaches ymax (which is the bottommost line).
Part 2
Same thing, but this time maxY is ymax + 1 (one cell above the floor). And I count until the position reaches the source.
I add 1 to the count because the sand that reaches the source should still be counted.