Spaces:
Running
Running
File size: 1,920 Bytes
a4da721 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
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) |