From 529a66e33b1201f22310f9c380536b03091eab12 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Tue, 13 Dec 2022 10:03:25 +0100 Subject: [PATCH] 2022: d13: ex1: add solution --- 2022/d13/ex1/ex1.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100755 2022/d13/ex1/ex1.py diff --git a/2022/d13/ex1/ex1.py b/2022/d13/ex1/ex1.py new file mode 100755 index 0000000..48fef3a --- /dev/null +++ b/2022/d13/ex1/ex1.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +import sys +from typing import Union + +Packet = Union[int, list["Packet"]] + + +def cmp_packet(lhs: Packet, rhs: Packet) -> int: + if isinstance(lhs, int) and isinstance(rhs, int): + return lhs - rhs + if isinstance(lhs, int): + lhs = [lhs] + if isinstance(rhs, int): + rhs = [rhs] + non_equal_cmp = (res for res in map(cmp_packet, lhs, rhs) if res != 0) + len_cmp = cmp_packet(len(lhs), len(rhs)) + return next(non_equal_cmp, len_cmp) + + +def solve(input: list[str]) -> int: + def to_packets(input: str) -> tuple[Packet, Packet]: + first, second = input.splitlines() + return eval(first), eval(second) # Secret best way to parse JSON + + return sum( + i + for i, packets in enumerate(input, start=1) + if cmp_packet(*to_packets(packets)) <= 0 + ) + + +def main() -> None: + input = sys.stdin.read().split("\n\n") + print(solve(input)) + + +if __name__ == "__main__": + main()