Skip to content

Instantly share code, notes, and snippets.

@Mu-adventofcode
Created June 8, 2022 19:12
Show Gist options
  • Save Mu-adventofcode/62d9d94c78b397ec9d9c7d5e3cce9aa7 to your computer and use it in GitHub Desktop.
Save Mu-adventofcode/62d9d94c78b397ec9d9c7d5e3cce9aa7 to your computer and use it in GitHub Desktop.
Advent of Code day 18 part 1
"""
This is essentially @benediktwerner's solution. I only did a few
renames and refactoring to get to understand how it works.
"""
import json
import functools
def add(n1, n2):
return reduction([n1, n2])
def reduction(num):
while True:
_, num, _, exploded = ignite(num)
if not exploded:
num, splitted = split(num)
if not splitted:
break
return num
def lsum(tail, t):
if t is None:
return tail
if isinstance(tail, int):
return tail + t
return [lsum(tail[0], t), tail[1]]
def rsum(head, h):
if h is None:
return head
if isinstance(head, int):
return head + h
return [head[0], rsum(head[1], h)]
def ignite(num, depth=0):
if isinstance(num, int):
return None, num, None, False
if depth == 4:
return num[0], 0, num[1], True
pre, mid0, post, exploded = ignite(num[0], depth + 1)
if exploded:
return pre, [mid0, lsum(num[1], post)], None, True
pre, mid1, post, exploded = ignite(num[1], depth + 1)
if exploded:
return None, [rsum(mid0, pre), mid1], post, True
return None, num, None, False
def split(num):
if isinstance(num, int):
if num < 10:
return num, False
return [(num // 2), num - (num // 2)], True
head, splitted = split(num[0])
if splitted:
return [head, num[1]], True
tail, splitted = split(num[1])
if splitted:
return [num[0], tail], True
return num, False
def magn(num):
m0 = num[0] if isinstance(num[0], int) else magn(num[0])
m1 = num[1] if isinstance(num[1], int) else magn(num[1])
return 3 * m0 + 2 * m1
lines = open("input_18.txt").read().splitlines()
total = functools.reduce(add, map(json.loads, lines))
print(magn(total))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment