Day 3 completed (I left the debug code)

This commit is contained in:
Fedaya 2024-12-03 07:07:25 +01:00
parent f37e249160
commit defa32fc9c
3 changed files with 59 additions and 0 deletions

3
day3/common.py Normal file
View File

@ -0,0 +1,3 @@
def parse(filename: str) -> str:
with open(filename) as f:
return f.read()

18
day3/part1.py Executable file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env python
import re
from common import parse
def solve(input: str) -> int:
regex = r"mul\((\d+),(\d+)\)"
muls = re.findall(regex, input)
return sum(map(lambda x: int(x[0]) * int(x[1]), muls))
def main():
print(solve(parse("input")))
if __name__ == "__main__":
main()

38
day3/part2.py Executable file
View File

@ -0,0 +1,38 @@
#!/usr/bin/env python
import re
from common import parse
def solve(input: str, debug=False) -> int:
regex = r"(mul\((\d+),(\d+)\)|do\(\)|don't\(\))"
prog = re.findall(regex, input)
the_sum = 0
enabled = True
for inst in prog:
if debug:
print(inst[0], end=": ")
if enabled and inst[0].startswith("mul"):
if debug:
print("multiplying")
the_sum += int(inst[1]) * int(inst[2])
elif enabled and inst[0] == "don't()":
if debug:
print("disabling")
enabled = False
elif not enabled and inst[0] == "do()":
if debug:
print("enabling")
enabled = True
else:
if debug:
print("noop")
return the_sum
def main():
print(solve(parse("input")))
if __name__ == "__main__":
main()