From 016048bc8009016fa3b8748e3afd2ac7a3daf9e3 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 18 Dec 2021 23:37:23 +0000 Subject: day 18: now more confusing --- 18.py | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/18.py b/18.py index 57d06ce..59c3f8a 100644 --- a/18.py +++ b/18.py @@ -30,19 +30,14 @@ with open_day(18) as f: homework = [parse(l) for l in f] def try_explode(n): - def try_add(n, val, primary, secondary): + def try_add(n, val, access, primary, secondary): if val == 0: return 0 - if is_pair(primary(n)): - val = try_add(primary(n), val, primary, secondary) - else: - primary(n, primary(n) + val) + content = access(n) + if not is_pair(content): + access(n, content + val) return 0 - if val != 0: - if is_pair(secondary(n)): - val = try_add(secondary(n), val, primary, secondary) - else: - secondary(n, secondary(n) + val) - return 0 + val = try_add(content, val, primary, primary, secondary) + val = try_add(content, val, secondary, primary, secondary) return val def descend(n, depth=0): if not is_pair(n): return None @@ -50,18 +45,12 @@ def try_explode(n): car_val = descend(n.car, depth + 1) if car_val is not None: if depth == 3: n.car = 0 - if not is_pair(n.cdr): - n.cdr += car_val.cdr - car_val.cdr = 0 - return Pair(car_val.car, try_add(n.cdr, car_val.cdr, car, cdr)) + return Pair(car_val.car, try_add(n, car_val.cdr, cdr, car, cdr)) else: cdr_val = descend(n.cdr, depth + 1) if cdr_val is not None: if depth == 3: n.cdr = 0 - if not is_pair(n.car): - n.car += cdr_val.car - cdr_val.car = 0 - return Pair(try_add(n.car, cdr_val.car, cdr, car), cdr_val.cdr) + return Pair(try_add(n, cdr_val.car, car, cdr, car), cdr_val.cdr) return descend(n) tests = [ -- cgit v1.2.3-54-g00ecf