1
0
Fork 0
adventofcode/2024/03/main.py

53 lines
1.3 KiB
Python
Raw Normal View History

2024-12-06 12:06:10 +00:00
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Author: Sebastian Mark
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string
import re
def readinput() -> str:
with open("input", "r", encoding="utf-8") as file:
lines = file.read()
return lines
def find_and_execute_instructions(m: str) -> int:
regex = r"mul\((\d{1,3}),(\d{1,3})\)"
res = sum(int(inst[0]) * int(inst[1]) for inst in re.findall(regex, m))
return res
def find_and_execute_enabled_instructions(m: str) -> int:
regex = r"mul\(\d{1,3},\d{1,3}\)|do\(\)|don't\(\)"
res = 0
allowed = True
for inst in re.findall(regex, m):
if inst.startswith("mul"):
if allowed:
res += find_and_execute_instructions(inst)
else:
allowed = inst.startswith("do()")
return res
def main():
currupted_memory = readinput()
# part 1
instructions_result = find_and_execute_instructions(currupted_memory)
print("Result: %d" % instructions_result)
# part 2
instructions_result = find_and_execute_enabled_instructions(currupted_memory)
print("Result (only enabled): %d" % instructions_result)
if __name__ == "__main__":
main()