Advent of code Day 3: Mull It Over

The Story

"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.

The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"

The Problem

The computer appears to be trying to run a program, but its memory is corrupted. All the instructions are jumbled up! The goal of the program is to multiply numbers using instructions like mul(X, Y). However, the memory has many invalid characters that should be ignored.

Your task is to find and process only valid mul instructions.

Examples

Example 1

Memory: xmul(2,4)%&mul[3,7]!@^mul(5,5)+mul(11,8)

Valid instructions: mul(2,4), mul(5,5), mul(11,8)

Result: 2×4 + 5×5 + 11×8 = 121

Example 2 (With Conditions)

Memory: xmul(2,4)&mul[3,7]!^don't()mul(5,5)+mul(11,8)do()mul(8,5)

Valid instructions: mul(2,4), mul(8,5)

Result: 2×4 + 8×5 = 48

Code Implementation

Part 1: Basic Multiplication


import re
with open("src\\day-3\\input.txt", "r") as file:
    courp_mem = file.read()
pattern = r"mul\((\d{1,3}),(\d{1,3})\)"
matches = re.findall(pattern, courp_mem)
print(matches)
res_sum = 0
for x, y in matches:
    res_sum += int(x) * int(y)
print(res_sum)
        

Part 2: Handling Conditions


import re

with open("src\\day-3\\input.txt", "r") as file:
    corrupted_memory = file.read()

pattern = r"mul\((\d{1,3}),(\d{1,3})\)" # Grouping
control_pattern = r"(do\(\)|don't\(\))"

all_matches = re.findall(f"{control_pattern}|{pattern}", corrupted_memory)
# print(all_matches)

result_sum = 0
mul_enabled = True

for match in all_matches:
    if match[0]:
        if match[0] == "do()":
            mul_enabled = True
        elif match[0] == "don't()":
            mul_enabled = False
    elif match[1] and match[2]:
        if mul_enabled:
            x, y = int(match[1]), int(match[2])
            result_sum += x * y

print(result_sum)