TechWorkRamblings

by Mike Kalvas

202412030000 Advent of Code 2024 Day 03

Mull It Over

Today we're visiting the toboggan rental shop from 2020 day 2 and need to help the elves with corrupted data in their computers.

#blog #project

The Puzzle

Today we're visiting the toboggan rental shop from 2020 day 2 and need to help the elves with corrupted data in their computers.

We're given a string a corrupted junk and need to pull out valid commands — formatted mul(\d{1,3},\d{1,3}) — and execute them.

Solution

Regex reigns supreme today.

const INSTRUCTIONS = /mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don't\(\)/g;
const getMatches = (input) => input.join().match(INSTRUCTIONS);
const getProduct = (s) => (s.match(/\d{1,3}/g) ?? [0]).product();

export const solutionOne = (input) => getMatches(input).map(getProduct).sum();

The do() and don't() capture groups are for part 2, so you can ignore those for now. The solution is to run a regex on the input string of corrupted data, pulling out matches of the mul commands, then map over those to extract the digits which we multiply together. Finally we sum those products up to get the answer.

Part Two

The second half of today's puzzle uses the strings do() and don't() to enable and disable the mul commands that follow it. We need to loop through our matches (including the capture groups that were unnecessary in the first part), toggling the enabled switch on and off as appropriate.

export const solutionTwo = (input) => {
  let sum = 0;
  let enabled = true;
  for (const match of getMatches(input)) {
    if (match === 'do()') {
      enabled = true;
    } else if (match === "don't()") {
      enabled = false;
    } else if (enabled) {
      sum += getProduct(match);
    }
  }
  return sum;
};

This one takes a little more code, but it's trivial stuff so I think it reads pretty well anyway. There's definitely a few more ways to do this. One might be to regex everything out at once. Another might be to use something like 0 and 1 for the enabled switch multiplying it to each product to nullify the disabled commands. I didn't think of anything that was particularly elegant or readable so I just left it here.


Getting back into the groove a little more than the past two days. I liked the outcome of this one.

You can find the full solutions to today's AoC puzzles in my AoC GitHub repo.