summaryrefslogtreecommitdiffstats
path: root/13.py
blob: 9282fdf9a159549ca1c7465f0833c90eebb08d7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from utils import open_day
from ast import literal_eval
from functools import cmp_to_key
from itertools import chain

with open_day(13) as f:
    pairs = [tuple(literal_eval(v) for v in p.split('\n')) for p in f.read().rstrip().split('\n\n')]

def compare(l, r):
    match (l, r):
        case (  [*l],   [*r]):
            for a, b in zip(l, r):
                cmp = compare(a,  b)
                if cmp != 0: return cmp
            return compare(len(l), len(r))
        case (  [*l], int(r)): return compare(l, [r])
        case (int(l),   [*r]): return compare([l], r)
        case (int(l), int(r)): return min(max(l - r, -1), 1)

p1 = 0
for i, (l, r) in enumerate(pairs):
    cmp = compare(l, r)
    if cmp < 0: p1 += i + 1
print(p1)

p2 = [[[2]], [[6]], *chain.from_iterable(pairs)]
p2.sort(key=cmp_to_key(compare))
print((p2.index([[2]]) + 1) * (p2.index([[6]]) + 1))