summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTomasz Kramkowski <tk@the-tk.com>2021-12-18 23:37:23 +0000
committerTomasz Kramkowski <tk@the-tk.com>2021-12-18 23:37:23 +0000
commit016048bc8009016fa3b8748e3afd2ac7a3daf9e3 (patch)
treeb798cd9119addb560b42581833fcfc0b1d18f56c
parentba48f135e0b52364c1ac765b227a06b8921a36c1 (diff)
downloadaoc2021-016048bc8009016fa3b8748e3afd2ac7a3daf9e3.tar.gz
aoc2021-016048bc8009016fa3b8748e3afd2ac7a3daf9e3.tar.xz
aoc2021-016048bc8009016fa3b8748e3afd2ac7a3daf9e3.zip
day 18: now more confusing
-rw-r--r--18.py27
1 files 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 = [