From aa8cb3092041ba8d293df7d15ebcad5b94fb1885 Mon Sep 17 00:00:00 2001 From: Heiko Ludwig Date: Tue, 3 Dec 2024 19:47:16 +0100 Subject: [PATCH] solve day 3 part 2 --- day_03/program.py | 31 ++++++++++++++++++++++++++----- day_03/sample-input.txt | 2 +- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/day_03/program.py b/day_03/program.py index 10b2ad9..e990273 100755 --- a/day_03/program.py +++ b/day_03/program.py @@ -10,17 +10,38 @@ def get_lines(filename: str) -> list: return [line.strip() for line in file.readlines()] -def main(): - # lines = get_lines("sample-input.txt") - lines = get_lines("input.txt") - +def part1_get_result_sum(lines: list) -> int: result_sum = 0 for line in lines: matches = re.findall(r"mul\((\d+),(\d+)\)", line) for match in matches: result_sum += int(match[0]) * int(match[1]) + return result_sum - print("Part 1: The sum of the results is", result_sum) + +def part2_get_result_sum(lines: list) -> int: + result_sum = 0 + active = True + pattern = re.compile(r"mul\((\d{1,3}),(\d{1,3})$") + for line in lines: + chunks = line.split(")") + for chunk in chunks: + if active: + if chunk.endswith("don't("): + active = False + elif match := re.search(pattern, chunk): + result_sum += int(match.group(1)) * int(match.group(2)) + elif chunk.endswith("do("): + active = True + return result_sum + + +def main(): + # lines = get_lines("sample-input.txt") + lines = get_lines("input.txt") + + print("Part 1: The sum of the results is", part1_get_result_sum(lines)) + print("Part 2: The sum of the results is", part2_get_result_sum(lines)) if __name__ == '__main__': diff --git a/day_03/sample-input.txt b/day_03/sample-input.txt index f274bda..30032cb 100644 --- a/day_03/sample-input.txt +++ b/day_03/sample-input.txt @@ -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))