Day 3 - Advent of Code 2024

Working solutions for the day 3 puzzles.

Part One

""" day_03_01.py """

# usage: python3 day_03_01.py < input

import re
import sys


def multiply(expression):
    """ mul(x,y) = x * y """
    args = re.findall(r'\d+', expression)
    return int(args[0]) * int(args[1])


with sys.stdin as infile:
    corrupted = infile.read()

instructions = re.findall(r'mul\(\d{1,3},\d{1,3}\)', corrupted)

print(sum(multiply(instruction) for instruction in instructions))

Part Two

""" day_03_02.py """

# usage: python3 day_03_02.py < input

import re
import sys


def multiply(expression):
    """ mul(x,y) = x * y """
    args = re.findall(r'\d+', expression)
    return int(args[0]) * int(args[1])


with sys.stdin as infile:
    corrupted = infile.read()

ops = r'mul\(\d{1,3},\d{1,3}\)|don\'t\(\)|do\(\)'
instructions = re.findall(ops, corrupted)

skip = False
total = 0
for instruction in instructions:
    match instruction:
        case 'do()':
            skip = False
        case 'don\'t()':
            skip = True
        case _:
            total += 0 if skip else multiply(instruction)

print(total)