-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<x>\d+),(?P<y>\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) |