This repository has been archived on 2024-12-22. You can view files and clone it, but cannot push or open issues or pull requests.
aoc2023/d4.py
2023-12-06 11:47:04 -05:00

70 lines
1.8 KiB
Python

from string import ascii_lowercase, ascii_uppercase, digits
import re
EXAMPLE = """
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
"""
def clean(text: str) -> list[str]:
return list(filter(lambda l: l.strip() != "", text.splitlines()))
def solve(lines: list[str]):
res = 0
for (i, line) in enumerate(lines):
c, s = line.split(":")
w, y = s.split("|")
w = set([int(c) for c in w.strip().split()])
y = set([int(c) for c in y.strip().split()])
z = w.intersection(y)
if z:
ps = 1
else:
ps = 0
for _ in range(len(z) - 1):
ps *= 2
res += ps
return res
def solve2(lines: list[str]):
res = 0
matches = []
for (i, line) in enumerate(lines):
c, s = line.split(":")
w, y = s.split("|")
w = set([int(c) for c in w.strip().split()])
y = set([int(c) for c in y.strip().split()])
z = w.intersection(y)
matches.append(len(z))
scratchcards = list(range(len(matches)))
while scratchcards:
sc = scratchcards.pop()
res += 1
for i in range(matches[sc]):
if sc + i + 1 < len(matches):
scratchcards.append(sc + i + 1)
return res
def main():
example = clean(EXAMPLE)
print("Example 1:", solve(example))
data = clean(open("i4.txt").read())
print("Solution 1:", solve(data))
example = clean(EXAMPLE)
print("Example 2:", solve2(example))
data = clean(open("i4.txt").read())
print("Solution 2:", solve2(data))
return
if __name__ == "__main__":
main()