Advent of Code 2024 - Day 2Red-Nosed Reports
| Problem statement | Source code | Tags: Mathematics
This problem pays tribute to 2015 day 19 (unimplemented).
Part 1
There are three types of neighbor difference : increasing (), decreasing (), and invalid. I can parse the successive differences to this structural representation, which makes subsequent analysis easier.
For part 1, we just need lists that are all Inc or all Dec.
Part 2
Now we want to delete a single element from the list to make it safe. Obviously there's an solution where we try deleting each element and checking if the result is safe. But we can do better.
For starters, deleting an element can only fix one invalid difference, or two that share an endpoint. So if there are two invalid differences that don't share an endpoint, we can immediately return false. Otherwise, we can try deleting the shared endpoint (or either endpoint if there's just one invalid difference), which removes and , replacing them with (if and ). If or , the resulting list is automatically safe; otherwise, we need to check if is compatible with the remaining differences.
Other than those that are straight Invalid, a difference may also be invalid because it's incompatible with the other differences. Therefore, our first step is to group all differences by type so we can identify the incompatible ones.
Now, there are the following cases:
- All increasing, plus two invalid or one invalid and one decreasing: delete the shared endpoint, and validate that is increasing.
- All decreasing, plus two invalid or one invalid and one increasing: delete the shared endpoint, and validate that is decreasing.
- All increasing, plus one invalid or one decreasing: if the invalid difference is at the start or end, we can delete the first or last element, respectively. Otherwise, we can delete either endpoint and check if the resulting difference is increasing.
- All decreasing, plus one invalid or one increasing: similar to the above.
- Already all increasing or all decreasing: return true.
- Otherwise, return false.