From b9e9de3b243bf18d440bc58991756f279098242c Mon Sep 17 00:00:00 2001 From: vsedov Date: Tue, 3 Dec 2024 13:03:06 +0000 Subject: [PATCH] day 03 --- src/aoc/aoc2024/day_03.py | 44 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/aoc/aoc2024/day_03.py b/src/aoc/aoc2024/day_03.py index 8a6e5cc..4131d14 100644 --- a/src/aoc/aoc2024/day_03.py +++ b/src/aoc/aoc2024/day_03.py @@ -1 +1,45 @@ +import math +import re +from itertools import compress, starmap +from operator import methodcaller, mul +from typing import Iterator, Match + +from src.aoc.aoc2024 import YEAR, get_day +from src.aoc.aoc_helper import Aoc + +MUL = re.compile(r"mul\((?P\d+),(?P\d+)\)") +INSTRUCTION = re.compile(r"mul\(\d+,\d+\)|do\(\)|don't\(\)") + + +def instruction_processor(matches: Iterator[Match]) -> Iterator[int]: + instructions = map(methodcaller("group", 0), matches) + enabled_states = [] + state = True + + for instr in instructions: + if instr == "do()": + state = True + elif instr == "don't()": + state = False + else: + enabled_states.append(state) if state and (nums := MUL.match(instr)): + yield math.prod(map(int, nums.groups())) + + +def part_a(txt: str) -> int: + return sum(math.prod(map(int, m)) for m in MUL.findall(txt)) + + +def part_b(txt: str) -> int: + return sum(instruction_processor(INSTRUCTION.finditer(txt))) + + +def main(txt: str) -> None: + print("part_a: ", part_a(txt)) + print("part_b: ", part_b(txt)) + + +if __name__ == "__main__": + aoc = Aoc(day=get_day(), years=YEAR) + aoc.run(main, submit=True, part="both", readme_update=True)