-
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.
feat: add second solution for 2024/3
- Loading branch information
1 parent
6f5a8ca
commit 3256b4d
Showing
2 changed files
with
47 additions
and
1 deletion.
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 |
---|---|---|
@@ -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())) |
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 @@ | ||
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)) |