advent24-llm / day03 /solution_claude-3-5-sonnet-20241022.py
jerpint's picture
Add solution files
a4da721
import re
def parse_multiplications(text):
# Find all valid mul(X,Y) patterns where X and Y are 1-3 digit numbers
pattern = r'mul\((\d{1,3}),(\d{1,3})\)'
matches = re.finditer(pattern, text)
total = 0
for match in matches:
x, y = int(match.group(1)), int(match.group(2))
total += x * y
return total
def parse_with_conditionals(text):
# Find all instructions in order
mul_pattern = r'mul\((\d{1,3}),(\d{1,3})\)'
do_pattern = r'do\(\)'
dont_pattern = r'don\'t\(\)'
# Combine all patterns
all_patterns = f'({mul_pattern}|{do_pattern}|{dont_pattern})'
matches = re.finditer(all_patterns, text)
enabled = True
total = 0
for match in matches:
full_match = match.group(0)
if full_match == 'do()':
enabled = True
elif full_match == "don't()":
enabled = False
else:
# It's a multiplication
if enabled:
x = int(match.group(2))
y = int(match.group(3))
total += x * y
return total
# Read input file
with open('./input.txt', 'r') as file:
content = file.read()
# Part 1
result1 = parse_multiplications(content)
print(str(result1))
# Part 2
result2 = parse_with_conditionals(content)
print(str(result2))