advent24-llm / day03 /solution_gpt-4o.py
jerpint's picture
Add solution files
a4da721
import re
def parse_instructions(memory):
# Regular expression to find valid mul(X,Y) instructions
mul_pattern = re.compile(r'mul\((\d{1,3}),(\d{1,3})\)')
# Regular expression to find do() and don't() instructions
do_pattern = re.compile(r'do\(\)')
dont_pattern = re.compile(r"don't\(\)")
# Find all mul instructions
mul_matches = mul_pattern.finditer(memory)
# Find all do() and don't() instructions
do_matches = list(do_pattern.finditer(memory))
dont_matches = list(dont_pattern.finditer(memory))
# Sort do and don't matches by their start position
control_matches = sorted(do_matches + dont_matches, key=lambda m: m.start())
# Part 1: Sum of all valid mul instructions
part1_sum = 0
for match in mul_matches:
x, y = int(match.group(1)), int(match.group(2))
part1_sum += x * y
# Part 2: Sum of enabled mul instructions
part2_sum = 0
mul_matches = mul_pattern.finditer(memory) # Re-iterate over mul matches
enabled = True # Initially, mul instructions are enabled
control_index = 0
for match in mul_matches:
# Check if there are any control instructions before this mul
while control_index < len(control_matches) and control_matches[control_index].start() < match.start():
if control_matches[control_index].group() == 'do()':
enabled = True
elif control_matches[control_index].group() == "don't()":
enabled = False
control_index += 1
if enabled:
x, y = int(match.group(1)), int(match.group(2))
part2_sum += x * y
return part1_sum, part2_sum
# Read the input file
with open('input.txt', 'r') as file:
memory = file.read()
# Get the results for both parts
result1, result2 = parse_instructions(memory)
# Print the results
print(result1)
print(result2)