From 6f8168631f79f99b8097d400b7ac6fe4cb3b0a68 Mon Sep 17 00:00:00 2001 From: Allianzcortex Date: Sat, 7 Dec 2024 09:56:16 -0500 Subject: [PATCH] add day7 solution --- advent_of_code/2024(python)/day7.py | 60 ++++++++++++++++++++++++ advent_of_code/2024(python)/test_day7.py | 27 +++++++++++ 2 files changed, 87 insertions(+) create mode 100644 advent_of_code/2024(python)/day7.py create mode 100644 advent_of_code/2024(python)/test_day7.py diff --git a/advent_of_code/2024(python)/day7.py b/advent_of_code/2024(python)/day7.py new file mode 100644 index 0000000..daa7333 --- /dev/null +++ b/advent_of_code/2024(python)/day7.py @@ -0,0 +1,60 @@ + + +def _is_equal_part1(target:int, nums:list[int], prefix:int)->bool: + if (not nums): + return prefix == target + + is_equal = False + + # we can do `*` or `+` 2 operators + prefix_mul = prefix*nums[0] + is_equal = is_equal or _is_equal_part1(target,nums[1:],prefix_mul) + + prefix_add = prefix+nums[0] + is_equal = is_equal or _is_equal_part1(target,nums[1:],prefix_add) + + return is_equal + + +def solve_day7_part1(matrix:list[str])->int: + res = 0 + for line in matrix: + expected_answer, given_input = line.split(":") + target = int(expected_answer) + nums = [int(num) for num in given_input.strip().split(" ")] + if _is_equal_part1(target, nums[1:],nums[0]): + res += target + + return res + + + +def _is_equal_part2(target:int, nums:list[int], prefix:int)->bool: + if (not nums): + return prefix == target + + is_equal = False + + # we can do `*` or `+` or `||` 3 operators + prefix_mul = prefix*nums[0] + is_equal = is_equal or _is_equal_part2(target,nums[1:],prefix_mul) + + prefix_add = prefix+nums[0] + is_equal = is_equal or _is_equal_part2(target,nums[1:],prefix_add) + + prefix_concat = int(str(prefix) + str(nums[0])) + is_equal = is_equal or _is_equal_part2(target,nums[1:],prefix_concat) + + return is_equal + + +def solve_day7_part2(matrix:list[str])->int: + res = 0 + for line in matrix: + expected_answer, given_input = line.split(":") + target = int(expected_answer) + nums = [int(num) for num in given_input.strip().split(" ")] + if _is_equal_part2(target, nums[1:],nums[0]): + res += target + + return res \ No newline at end of file diff --git a/advent_of_code/2024(python)/test_day7.py b/advent_of_code/2024(python)/test_day7.py new file mode 100644 index 0000000..721d640 --- /dev/null +++ b/advent_of_code/2024(python)/test_day7.py @@ -0,0 +1,27 @@ +import unittest + +from day7 import solve_day7_part1, solve_day7_part2 + + +input7 = [ +"190: 10 19", +"3267: 81 40 27", +"83: 17 5", +"156: 15 6", +"7290: 6 8 6 15", +"161011: 16 10 13", +"192: 17 8 14", +"21037: 9 7 18 13", +"292: 11 6 16 20", +] + +class TestDay7(unittest.TestCase): + + def test_part1(self): + self.assertEqual(solve_day7_part1(input7), 3749) + + def test_part2(self): + self.assertEqual(solve_day7_part2(input7), 11387) + +if __name__ == "__main__": + unittest.main()