aoc
/
2022
1
0
Fork 0
2022/day13.py

45 lines
1.0 KiB
Python

import fileinput
import json
from functools import cmp_to_key
from typing import Any
def main() -> None:
pairs = []
pair: list[list[Any]] = []
packets = [[[2]], [[6]]]
for line in fileinput.input():
if not line.strip():
pairs.append(pair)
pair = []
else:
obj = json.loads(line)
pair.append(obj)
packets.append(obj)
pairs.append(pair)
def cmp(xs: list[Any] | int, ys: list[Any] | int) -> int:
if isinstance(xs, int) and isinstance(ys, int):
return (xs > ys) - (xs < ys)
if isinstance(xs, int):
xs = [xs]
if isinstance(ys, int):
ys = [ys]
for x, y in zip(xs, ys):
if result := cmp(x, y):
return result
return (len(xs) > len(ys)) - (len(xs) < len(ys))
print(sum(i + 1 for i, (xs, ys) in enumerate(pairs) if cmp(xs, ys) == -1))
packets.sort(key=cmp_to_key(cmp))
print((packets.index([[2]]) + 1) * (packets.index([[6]]) + 1))
main()