From 071ed13c4ff0c59b5fdea23e17c19cd302f8ce67 Mon Sep 17 00:00:00 2001 From: setop Date: Wed, 11 Dec 2024 12:38:29 +0100 Subject: [PATCH] day 7, make some --- d07/perfs.txt | 6 ++++++ d07/run.py | 17 ++++++++--------- d07/run_r.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 9 deletions(-) create mode 100644 d07/perfs.txt create mode 100644 d07/run_r.py diff --git a/d07/perfs.txt b/d07/perfs.txt new file mode 100644 index 0000000..5a6c7b0 --- /dev/null +++ b/d07/perfs.txt @@ -0,0 +1,6 @@ + + +awk '{print 3^(NF-2)}' input | sum0 +15'721'434 operations total +13'090'754 thanks to "any" +7'805'608 thanks to "target" diff --git a/d07/run.py b/d07/run.py index e534a68..dc17dba 100644 --- a/d07/run.py +++ b/d07/run.py @@ -1,30 +1,29 @@ import sys -from math import * +from typing import Generator as Gen PART2 = len(sys.argv)>1 and sys.argv[1] == "2" I = sys.stdin.read().strip().split("\n") -def conccat(a, b): +def conccat(a, b) -> int: # 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)) -def gen_nb(L:list[int]): +def gen_nb(L:list[int]) -> Gen[int, None, None]: if len(L) == 1: yield L[0] else: for x in gen_nb(L[:-1]): - yield L[-1] * x - yield L[-1] + x + yield x * L[-1] + yield x + L[-1] if PART2: yield conccat(x, L[-1]) S = 0 for l in I: - r, nb = l.split(":") - x = int(r) + x, nb = l.split(":") + x = int(x) nb = list(map(int,nb.strip().split(" "))) - S += x * any(x == a for a in gen_nb(nb)) + S += x * (1 if any(x == a for a in gen_nb(nb)) else 0) print(S) - diff --git a/d07/run_r.py b/d07/run_r.py new file mode 100644 index 0000000..03ef661 --- /dev/null +++ b/d07/run_r.py @@ -0,0 +1,35 @@ +import sys +from typing import Generator as Gen + +PART2 = len(sys.argv)>1 and sys.argv[1] == "2" +I = sys.stdin.read().strip().split("\n") + +def conccat(a, b) -> int: + # 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)) + +def gen_nb(L:list[int], target) -> Gen[int, None, None]: + if len(L) == 1: + yield L[0] + else: + for x in gen_nb(L[:-1], target): + z = x + L[-1] + if z <= target: + yield z + z = x * L[-1] + if z <= target: + yield z + if PART2: # concat is always bigger than mul, so it can be nested + z = conccat(x, L[-1]) + if z <= target: + yield z + +S = 0 +for l in I: + x, nb = l.split(":") + x = int(x) + nb = list(map(int,nb.strip().split(" "))) + S += x * (1 if any(x == a for a in gen_nb(nb, x)) else 0) +print(S)