AdventOfCode/2024/03/solution.py

27 lines
756 B
Python
Raw Normal View History

from aocd import get_data
import re
data = get_data(day=3, year=2024)
2024-12-03 14:56:29 -04:00
# Part one
matches = re.findall(r"mul\((\d+),(\d+)\)", data, re.MULTILINE)
total = 0
for match in matches:
total += int(match[0]) * int(match[1])
print(total)
2024-12-03 15:01:48 -04:00
# One-liner
# print(sum(int(x) * int(y) for x, y in re.findall(r"mul\((\d+),(\d+)\)", data, re.MULTILINE)))
2024-12-03 14:56:29 -04:00
# Part two
matches = re.finditer(r"mul\((\d+),(\d+)\)", data, re.MULTILINE)
total = 0
for match in matches:
start = match.start()
do_match = data.rfind("do()", 0, start)
dont_match = data.rfind("don't()", 0, start)
if do_match == dont_match == -1: # Neither
total += int(match.group(1)) * int(match.group(2))
2024-12-03 14:58:13 -04:00
elif do_match > dont_match: # Do
2024-12-03 14:56:29 -04:00
total += int(match.group(1)) * int(match.group(2))
print(total)