add 2024/day1-day5 python
This commit is contained in:
parent
6c64d1b62e
commit
7c4e98ebcf
5 changed files with 360 additions and 0 deletions
52
2024/03/main.py
Normal file
52
2024/03/main.py
Normal file
|
@ -0,0 +1,52 @@
|
|||
#!/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()
|
Loading…
Add table
Add a link
Reference in a new issue