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

  1. Get your input text into your programming environment, either programmatically or by copy/pasting.

  2. 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.

  3. Get a sum variable and set it to 0. This will hold the sum of your products, and it is the final thing we will return.

  4. Execute your regex against the input text. For each match, parse the digits and multiply them. Add the product to your sum variable.

  5. 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.

  1. Get a variable like enabled and set it to true, since we want to count any mul(x,y) values we find until we see a don't().

  2. .split() our input text into tokens (chunks of text) when we see a don't() or do() so that we can act on the chunks accordingly.

  3. For each token:

    • If the token is don't(), set enabled to false.
    • Else, if the token is do(), set enabled to true.
    • 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 enabled is true. If we hit this, it's time to do our multiplying and summing (see step 4 above).
  4. 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!