aoc2024/day07.py

42 lines
946 B
Python
Raw Permalink Normal View History

2024-12-07 06:58:09 +00:00
#!/usr/bin/env python3
from copy import copy
puzzle = []
with open("day07") as f:
for l in f:
(res, n) = l.split(':')
ns = list(map(int, n.strip().split(' ')))
puzzle.append((int(res), ns))
# 1
def calc(res, ns, cur):
if cur == res: return True
if cur > res: return False
if len(ns) == 0: return False
n = ns.pop(0)
return calc(res, copy(ns), cur+n) or calc(res, copy(ns), cur*n)
res = 0
for p in puzzle:
if calc(p[0], copy(p[1][1:]), p[1][0]):
res += p[0]
print(res)
# 2
def calc2(res, ns, cur):
if len(ns) == 0 and res == cur: return True
if cur > res: return False
if len(ns) == 0: return False
n = ns[0]
return (calc2(res, copy(ns[1:]), cur+n)
or calc2(res, copy(ns[1:]), cur*n)
or calc2(res, copy(ns[1:]), int(str(cur)+str(n))))
res = 0
for p in puzzle:
if calc2(p[0], copy(p[1][1:]), p[1][0]):
res += p[0]
print(res)