diff --git a/puzzles/1.py b/puzzles/1.py index 7cecb4b..5f96947 100644 --- a/puzzles/1.py +++ b/puzzles/1.py @@ -1,6 +1,6 @@ from collections import Counter -test_input = """ +test_input_p1 = test_input_p2 = """ 3 4 4 3 2 5 diff --git a/puzzles/2.py b/puzzles/2.py index 4bff707..3bdc50f 100644 --- a/puzzles/2.py +++ b/puzzles/2.py @@ -1,8 +1,9 @@ from itertools import islice from typing import Iterator + from more_itertools import ilen -test_input = """ +test_input_p1 = test_input_p2 = """ 7 6 4 2 1 1 2 7 8 9 9 7 6 2 1 diff --git a/puzzles/3.py b/puzzles/3.py new file mode 100644 index 0000000..4ce1f55 --- /dev/null +++ b/puzzles/3.py @@ -0,0 +1,35 @@ +import re +from functools import reduce + +test_input_p1 = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))" +test_input_p2 = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))" + +test_solution_p1 = 161 +test_solution_p2 = 48 + +instruction_pattern = re.compile(r"mul\((\d+),(\d+)\)|(do(?:n't)?)\(\)") + + +def solve_p1(puzzle_input: str) -> int: + instructions = ( + tuple(map(int, match[:2])) + for match in instruction_pattern.findall(puzzle_input) + if match[0] + ) + return sum(a * b for a, b in instructions) + + +def solve_p2(puzzle_input: str) -> int: + instructions = ( + match[2] or tuple(map(int, match[:2])) + for match in instruction_pattern.findall(puzzle_input) + ) + return reduce( + lambda a, i: ( + (1 if i == "do" else 0, a[1]) + if isinstance(i, str) + else (a[0], a[1] + a[0] * i[0] * i[1]) + ), + instructions, + (1, 0), + )[1] diff --git a/solve.py b/solve.py index 0eb837b..c533a8b 100644 --- a/solve.py +++ b/solve.py @@ -32,12 +32,12 @@ def main(): try: print("Testing part 1 solution...") start = time() - assert mod.solve_p1(mod.test_input) == mod.test_solution_p1 + assert mod.solve_p1(mod.test_input_p1) == mod.test_solution_p1 print(f"Test passed in {time() - start:.3f} seconds") print("Testing part 2 solution...") start = time() - assert mod.solve_p2(mod.test_input) == mod.test_solution_p2 + assert mod.solve_p2(mod.test_input_p2) == mod.test_solution_p2 print(f"Test passed in {time() - start:.3f} seconds") except AssertionError: