From f0fdbb6161528b1af75479a7833251713fd4ea9b Mon Sep 17 00:00:00 2001 From: Armin Friedl Date: Sat, 7 Dec 2024 07:58:09 +0100 Subject: [PATCH] Day07 --- day07.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 day07.py diff --git a/day07.py b/day07.py new file mode 100644 index 0000000..f0967af --- /dev/null +++ b/day07.py @@ -0,0 +1,41 @@ +#!/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)