64 lines
1.6 KiB
Python
64 lines
1.6 KiB
Python
from functools import cmp_to_key
|
|
from json import loads
|
|
from tools.aoc import AOCDay
|
|
from tools.tools import compare
|
|
from typing import Any
|
|
|
|
|
|
def packet_compare(left: list, right: list) -> int:
|
|
for l_value, r_value in zip(left, right):
|
|
if l_value == r_value:
|
|
continue
|
|
|
|
match l_value, r_value:
|
|
case int(), int():
|
|
return compare(l_value, r_value)
|
|
case int(), list():
|
|
l_value = [l_value]
|
|
case list(), int():
|
|
r_value = [r_value]
|
|
|
|
if c := packet_compare(l_value, r_value):
|
|
return c
|
|
|
|
return compare(len(left), len(right))
|
|
|
|
|
|
class Day(AOCDay):
|
|
inputs = [
|
|
[
|
|
(13, "input13_test"),
|
|
(5806, "input13_dennis"),
|
|
(6428, "input13"),
|
|
],
|
|
[
|
|
(140, "input13_test"),
|
|
(23600, "input13_dennis"),
|
|
(22464, "input13"),
|
|
]
|
|
]
|
|
|
|
def parse_input(self) -> list:
|
|
return [loads(x) for x in self.getInput() if x]
|
|
|
|
def part1(self) -> Any:
|
|
packets = self.parse_input()
|
|
index_sum = 0
|
|
for x in range(len(packets) // 2):
|
|
if packet_compare(packets[x * 2], packets[x * 2 + 1]) < 1:
|
|
index_sum += x + 1
|
|
|
|
return index_sum
|
|
|
|
def part2(self) -> Any:
|
|
packets = self.parse_input()
|
|
packets.extend([[[2]], [[6]]])
|
|
packets.sort(key=cmp_to_key(packet_compare))
|
|
|
|
return (packets.index([[2]]) + 1) * (packets.index([[6]]) + 1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
day = Day(2022, 13)
|
|
day.run(verbose=True)
|