From e73cd1d2fe83d2de1f288707b1f6f17d94746878 Mon Sep 17 00:00:00 2001 From: Bradley Reynolds Date: Thu, 5 Dec 2024 02:20:29 +0000 Subject: [PATCH] AOC 2024 03 Signed-off-by: GitHub --- .../2024/03/python/aoc_2024_03.py | 34 +++++++++++++++++++ .../2024/03/python/test_aoc_2024_03.py | 9 +++++ 2 files changed, 43 insertions(+) create mode 100644 events/advent_of_code/2024/03/python/aoc_2024_03.py create mode 100644 events/advent_of_code/2024/03/python/test_aoc_2024_03.py diff --git a/events/advent_of_code/2024/03/python/aoc_2024_03.py b/events/advent_of_code/2024/03/python/aoc_2024_03.py new file mode 100644 index 0000000..2f42bd2 --- /dev/null +++ b/events/advent_of_code/2024/03/python/aoc_2024_03.py @@ -0,0 +1,34 @@ +import re +from math import prod +from pathlib import Path + + +def part1(text: str) -> int: + return sum(int(x) * int(y) for x, y in re.findall(r"mul\((\d{1,3}),(\d{1,3})\)", text, re.MULTILINE)) + + +def part2(text: str) -> int: + do_indexes = [match.start(0) for match in re.finditer(r"do\(\)", text)] + dont_indexes = [match.start(0) for match in re.finditer(r"don't\(\)", text)] + map_ = [True] * len(text) + in_do = True + for counter in range(len(map_)): + if counter in do_indexes: + in_do = True + elif counter in dont_indexes: + in_do = False + else: + pass + map_[counter] = in_do + + return sum( + prod(map(int, match.groups())) + for match in re.finditer(r"mul\((\d{1,3}),(\d{1,3})\)", text, re.MULTILINE) + if map_[match.start(0)] + ) + + +if __name__ == "__main__": + text = Path("../input.txt").read_text(encoding="locale") + print(part1(text)) + print(part2(text)) diff --git a/events/advent_of_code/2024/03/python/test_aoc_2024_03.py b/events/advent_of_code/2024/03/python/test_aoc_2024_03.py new file mode 100644 index 0000000..1185941 --- /dev/null +++ b/events/advent_of_code/2024/03/python/test_aoc_2024_03.py @@ -0,0 +1,9 @@ +from aoc_2024_03 import part1, part2 + + +def test_part1() -> None: + assert part1("xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))") == 161 + + +def test_part2() -> None: + assert part2("xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))") == 48