Diego A. Casas

Advent of Code 2024, Day 2

Index – Advent of Code

Part One

The puzzle input in this one is a list of reports. A report is a series of integers called levels and separated by spaces. They ask you to determine the number of safe reports. A safe report is defined as one in which its levels are all increasing or decreasing, and the difference between adjacent levels is at least 1 and at most 3.

My first 10 reports, of 1000 in total, are:

65 68 71 72 71
31 34 36 37 37
80 83 84 86 87 90 92 96
30 33 36 39 45
21 22 25 23 24
66 68 69 71 72 71 72 69
2 3 5 4 4
77 78 77 79 82 83 86 90
6 9 10 7 9 12 17
25 27 28 28 30 32

As with the previous puzzle, I used the Import function. I defined a boolean function called safeQ. Note that in Wolfram Language boolean functions (formally called predicates) ends with the letter Q, standing for Question. My function safeQ computes the successive level differences of a single report. Finally, it checks if the differences are all in the interval [1, 3] (all increasing) or [-3, -1] (all decreasing). The resulting code is the following:

reports = Import["input.txt", "Table"]

safeQ[report_] :=
    report //
    Differences //
    AllTrue[#, Between[{1, 3}]] || AllTrue[#, Between[{-1, -3}]]&

numberSafeReports = Count[reports, _?safeQ]

Three interesting details:

I found the number of safe reports to be 269.

Part Two

A new rule is introduced here. Now, if by removing one of the levels from a record, it becomes safe, the report is considered safe. This rule is called problem dampener. In order to implement this, I extended my original safeQ function. This new function computes all the reports resulting from removing a single element at a time from the original report. The Delete function helps in generating the candidates by deleting the ith element in the range provided by Table. Then, the original safeQ is applied to each one of the candidates to see if at least one of them is safe (AnyTrue).

problemDampenerSafeQ[report_] :=
    Table[Delete[report, i], {i, Length[report]}] // AnyTrue[safeQ]

numberActualSafeReports = Count[reports, _?problemDampenerSafeQ]

The number of safe reports considering the problem dampener was 337.