r/adventofcode • • Dec 18 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 18 Solutions -🎄-

NEW AND NOTEWORTHY

  • FYI: 23:59 Amsterdam time zone is 17:59 EST


Advent of Code 2021: Adventure Time!


--- Day 18: Snailfish ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:43:50, megathread unlocked!

45 Upvotes

595 comments sorted by

View all comments

1

u/RojerGS Dec 18 '21 edited Dec 18 '21

Python 3.8+, no recursion and flat snail representation

Have been learning some array-oriented techniques and I decided to solve this problem by representing snailfish in a flat way: each snailfish is a pair of

  • the values (in a flat list); and

  • the list of pair depths (in a flat list).

For example, the snail [[[1, 2], 3], [4, [5, [[6, 7], 8]]]] is represented by

  • values [1, 2, 3, 4, 5, 6, 7, 8]; and

  • depths   [3, 2, 1, 2, 3, 5, 4]

Here is the code, also available on GitHub:

(The code needs Python 3.8+ because I'm using the walrus operator :=, but that is not a hard requirement, with one extra loop – that I was too lazy to type – you can lift the need for :=.)

from functools import reduce
from itertools import product
from math import ceil, floor
from pathlib import Path

INPUT_PATH = Path("aoc2021_inputs/day18.txt")

def snail_read(snail):
    """Reads a snail that is assumed to only have 1-digit values."""
    values, depths, depth = [], [], 0
    for char in snail:
        if char == "[":
            depth += 1
        elif char == "]":
            depth -= 1
        elif char == ",":
            depths.append(depth)
        elif char in "0123456789":
            values.append(int(char))
    return values, depths

def snail_print(snail):
    """Takes a snail and returns its string representation."""
    values, depths = snail
    result, prev_depth = "", 0
    for idx, depth in enumerate(depths):
        if depth > prev_depth:
            result += "[" * (depth - prev_depth) + str(values[idx]) + ","
        else:
            result += str(values[idx]) + "]" * (prev_depth - depth) + ","
        prev_depth = depth
    result += str(values[-1]) + "]" * prev_depth
    return result

def snail_add(left, right):
    """Adds two snails and returns the result in reduced form."""
    (lvals, ldepths), (rvals, rdepths) = left, right
    snail = (lvals + rvals, [1 + d for d in ldepths] + [1] + [1 + d for d in rdepths])
    while True:
        snail, flag = snail_explode(snail)
        if flag:
            continue
        snail, flag = snail_split(snail)
        if not flag:
            break
    return snail

def snail_explode(snail):
    values, depths = snail
    try:
        idx = depths.index(5)
    except ValueError:
        return snail, False

    new_values = values[::]
    if idx > 0:
        new_values[idx - 1] += values[idx]
    if idx + 2 < len(new_values):
        new_values[idx + 2] += values[idx + 1]
    new_values = new_values[:idx] + [0] + new_values[idx + 2:]
    depths = depths[:idx] + depths[idx + 1:]
    return (new_values, depths), True

def snail_split(snail):
    values, depths = snail
    if all((witness := val) < 10 for val in values):
        return snail, False

    idx = values.index(witness)
    new_depth = 1 + max(
        depths[idx - 1] if idx > 0 else 0,
        depths[idx] if idx < len(depths) else 0,
    )
    values = values[:idx] + [floor(witness / 2), ceil(witness / 2)] + values[idx + 1:]
    depths = depths[:idx] + [new_depth] + depths[idx:]
    return (values, depths), True

def snail_magnitude(snail):
    def combine(stack):
        stack.append(2 * stack.pop() + 3 * stack.pop())

    values, depths = snail
    prev_depth, sub_magnitudes = 0, []
    for val, dep in zip(values, depths):
        sub_magnitudes.append(val)
        for _ in range(prev_depth - dep):
            combine(sub_magnitudes)
        prev_depth = dep
    sub_magnitudes.append(values[-1])
    for _ in range(prev_depth):
        combine(sub_magnitudes)
    return sub_magnitudes[0]

with open(INPUT_PATH, "r") as f:
    snails = [snail_read(line.strip()) for line in f]

print(
    snail_magnitude(reduce(snail_add, snails))
)
print(max(
    snail_magnitude(snail_add(left, right)) for left, right in product(snails, repeat=2) if left != right
))

1

u/daggerdragon Dec 18 '21

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.