diff options
-rw-r--r-- | 18.py | 27 |
1 files changed, 8 insertions, 19 deletions
@@ -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 = [ |