zerosleeps

Since 2010

Advent of Code 2022 day 13

Not-quite-working solution for Advent of Code 2022 day 13. Works for both parts of the example input, doesn’t work for my actual input. I’ll come back to this.

from functools import cmp_to_key
from utils import get_raw_input_as_str

def parse_raw_input(raw_input):
    return [[eval(packet) for packet in pair.splitlines()] for pair in raw_input.split("\n\n")]

def compare(left, right):
    if type(left) == type(right) == int:
        if left < right:
            return 1
        elif left > right:
            return -1
        else:
            return None
    elif type(left) == type(right) == list:
        result = None
        i = 0
        while result is None:
            if len(left) <= i and len(right) >= i:
                return 1
            elif len(right) <= i and len(left) >= i:
                return -1
            else:
                result = compare(left[i], right[i])
                i += 1
        return result
    elif type(left) == int and type(right) != int:
        return compare([left], right)
    elif type(right) == int and type(left) != int:
        return compare(left, [right])
    else:
        return None

def part_one(input):
    return sum([i + 1 for i, pair in enumerate(input) if compare(pair[0], pair[1]) == 1])

def part_two(input):
    flattened_input = [packet for pair in input for packet in pair] + [[[2]]] + [[[6]]]
    sorted_packets = sorted(flattened_input, key=cmp_to_key(compare), reverse=True)
    return (sorted_packets.index([[2]]) + 1) * (sorted_packets.index([[6]]) + 1)

if __name__ == '__main__':
    print(part_one(parse_raw_input(get_raw_input_as_str("day_13_input.txt"))))
    print(part_two(parse_raw_input(get_raw_input_as_str("day_13_input.txt"))))