diff --git a/2023/day04.py b/2023/day04.py new file mode 100644 index 0000000..1faf09e --- /dev/null +++ b/2023/day04.py @@ -0,0 +1,58 @@ +import re + +nums: list[list[int]] = [] +wins: list[list[int]] = [] + +copies: dict[int, int] = {} + + +def part1() -> int: + points: int = 0 + + for n in range(len(nums)): + x = list(filter(lambda y: y in wins[n], nums[n])) + + if len(x) != 0: + points += 2 ** (len(x) - 1) + + return points + + +def part2(c: int) -> int: + # base case + if len(nums) == c: + return sum(copies.values()) + else: + if c not in copies: + copies[c] = 1 + else: + copies[c] += 1 + + x = list(filter(lambda y: y in wins[c], nums[c])) + + if len(x) != 0: + for y in range(1, len(x) + 1): + if c + y not in copies: + copies[c + y] = 1 * copies[c] + else: + copies[c + y] += 1 * copies[c] + + return part2(c + 1) + + +def proc() -> None: + with open("day04.txt") as f: + for line in f: + line = line.strip() + + n = line.split(": ")[1].split(" | ")[0] + w = line.split(": ")[1].split(" | ")[1] + + nums.append(re.findall(r"\d+", n)) + wins.append(re.findall(r"\d+", w)) + + +if __name__ == "__main__": + proc() + print(part1()) + print(part2(0)) diff --git a/2023/day04_test.py b/2023/day04_test.py new file mode 100644 index 0000000..5f2a4a1 --- /dev/null +++ b/2023/day04_test.py @@ -0,0 +1,11 @@ +from day04 import * + +proc() + + +def test_part1() -> None: + assert part1() == 24542 + + +def test_part2() -> None: + assert part2(0) == 8736438