Skip to content

Commit

Permalink
feat: add second solution for 2024/3
Browse files Browse the repository at this point in the history
  • Loading branch information
hectcastro committed Dec 3, 2024
1 parent 6f5a8ca commit 3256b4d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
46 changes: 46 additions & 0 deletions 2024/3/2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import fileinput
import re
from collections import namedtuple
from fileinput import FileInput

MulInstruction = namedtuple("MulInstruction", ["pos", "x", "y"])
DoInstruction = namedtuple("DoInstruction", ["pos"])
DontInstruction = namedtuple("DontInstruction", ["pos"])


def handler(raw_instructions: FileInput) -> int:
pattern_mul = r"mul\((\d{1,3}),(\d{1,3})\)"
pattern_do = r"do\(\)"
pattern_dont = r"don\'t\(\)"

all_instructions = "".join(raw_instructions)

matches_mul = list(re.finditer(pattern_mul, all_instructions))
matches_do = list(re.finditer(pattern_do, all_instructions))
matches_dont = list(re.finditer(pattern_dont, all_instructions))

instructions = []

instructions.extend([MulInstruction(pos=m.start(), x=int(m.group(1)), y=int(m.group(2))) for m in matches_mul])
instructions.extend([DoInstruction(pos=m.start()) for m in matches_do])
instructions.extend([DontInstruction(pos=m.start()) for m in matches_dont])

instructions.sort(key=lambda x: x.pos)

instruction_enabled = True
total = 0

for instruction in instructions:
if isinstance(instruction, DoInstruction):
instruction_enabled = True
elif isinstance(instruction, DontInstruction):
instruction_enabled = False
elif isinstance(instruction, MulInstruction):
if instruction_enabled:
total += instruction.x * instruction.y

return total


if __name__ == "__main__":
print(handler(fileinput.input()))
2 changes: 1 addition & 1 deletion 2024/3/test_input.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))

0 comments on commit 3256b4d

Please sign in to comment.