Advent of Code 2024 day 3 strategy
Published
This article is for Day 3 of Advent of Code 2024, Mull It Over. Today's puzzle takes us to Regex Land, where presumably everybody is having to re-remember how to do regular expressions for the first time in a year. No cheats here, just strategy.
Part 1: Multiplying
-
Get your input text into your programming environment, either programmatically or by copy/pasting.
-
Write a regular expression (regex) in your language that looks for the text
mul, then an escaped left bracket\(, then a digit(\d+), a comma,, and another digit(\d+), plus an escaped right bracket\). Make sure to search your input globally/g. -
Get a
sumvariable and set it to 0. This will hold the sum of your products, and it is the final thing we will return. -
Execute your regex against the input text. For each match, parse the digits and multiply them. Add the product to your
sumvariable. -
Return the sum.
Part 2: The do's and don'ts of multiplying
Very similar, but this time you need to keep track of whether you "do" or "don't" want to count the particular mul(x,y) values. I called my boolean variable for this enabled.
Start with the same strategy up to part 3 above.
-
Get a variable like
enabledand set it totrue, since we want to count anymul(x,y)values we find until we see adon't(). -
.split()our input text into tokens (chunks of text) when we see adon't()ordo()so that we can act on the chunks accordingly. -
For each token:
- If the token is
don't(), setenabledtofalse. - Else, if the token is
do(), setenabledtotrue. - Now that we've dealt with the cases where our token is an enabler/disabler, we can check for the condition we really care about: else if
enabledis true. If we hit this, it's time to do our multiplying and summing (see step 4 above).
- If the token is
-
Return the sum.
Today will either be really horrific if you're not down with regex, or very easy if you have some familiarity with them. Best of luck!