aoc2024/d07/run.py

30 lines
753 B
Python
Raw Permalink Normal View History

2024-12-07 12:06:18 +00:00
import sys
2024-12-11 11:38:29 +00:00
from typing import Generator as Gen
2024-12-07 12:06:18 +00:00
PART2 = len(sys.argv)>1 and sys.argv[1] == "2"
I = sys.stdin.read().strip().split("\n")
2024-12-11 11:38:29 +00:00
def conccat(a, b) -> int:
2024-12-07 12:06:18 +00:00
# 12 345 become 12345
# return a * pow(10, ceil(log10(b))) + b <= breaksfor 1000
# but int <-> str convertions are slow (x4)
return int(str(a)+str(b))
2024-12-11 11:38:29 +00:00
def gen_nb(L:list[int]) -> Gen[int, None, None]:
2024-12-07 12:06:18 +00:00
if len(L) == 1:
yield L[0]
else:
for x in gen_nb(L[:-1]):
2024-12-11 11:38:29 +00:00
yield x * L[-1]
yield x + L[-1]
2024-12-07 12:06:18 +00:00
if PART2:
yield conccat(x, L[-1])
S = 0
for l in I:
2024-12-11 11:38:29 +00:00
x, nb = l.split(":")
x = int(x)
2024-12-07 12:06:18 +00:00
nb = list(map(int,nb.strip().split(" ")))
2024-12-11 11:38:29 +00:00
S += x * (1 if any(x == a for a in gen_nb(nb)) else 0)
2024-12-07 12:06:18 +00:00
print(S)