adventofcode2024/day03/sol.py

32 lines
837 B
Python
Raw Normal View History

2024-12-03 06:09:30 +00:00
import re
def solve(s):
pattern = re.compile(r'mul\(([0-9]{1,3}),([0-9]{1,3})\)')
muls = [(int(m[0]), int(m[1])) for m in pattern.findall(s)]
print(sum(x*y for x,y in muls))
def solve2(s):
pattern = re.compile(r"mul\(([0-9]{1,3}),([0-9]{1,3})\)|(do)\(\)|(don't)\(\)")
enabled = 1
muls = []
for x,y,do,dont in pattern.findall(s):
if do:
enabled = 1
elif dont:
enabled = 0
else:
if enabled:
muls.append((int(x),int(y)))
print(sum(x*y for x,y in muls))
sample = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"
input = open("input").read()
solve(sample)
solve(input)
sample = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
solve2(sample)
solve2(input)