aoc2022/day13.py
2022-12-13 06:55:09 +01:00

61 lines
1.6 KiB
Python

from functools import cmp_to_key
from tools.aoc import AOCDay
from tools.tools import compare
from typing import Any
def packet_compare(left: list, right: list, debug: int = 0) -> int:
for i in range(min(len(left), len(right))):
l_value = left[i]
r_value = right[i]
if isinstance(l_value, list) and isinstance(r_value, int):
r_value = [r_value]
elif isinstance(l_value, int) and isinstance(r_value, list):
l_value = [l_value]
if r_value != l_value:
if isinstance(l_value, int):
return compare(l_value, r_value)
else:
return packet_compare(l_value, r_value, debug + 1)
if len(left) != len(right):
return compare(len(left), len(right))
return -1
class Day(AOCDay):
inputs = [
[
(13, "input13_test"),
(6428, "input13"),
],
[
(140, "input13_test"),
(22464, "input13"),
]
]
def part1(self) -> Any:
packets = self.getMultiLineInputAsArray(eval)
index_sum = 0
for index, (left, right) in enumerate(packets):
if packet_compare(left, right) == -1:
index_sum += index + 1
return index_sum
def part2(self) -> Any:
packets = [eval(x) for x in self.getInput() if x]
packets.extend([[[2]], [[6]]])
sorted_packets = sorted(packets, key=cmp_to_key(packet_compare))
return (sorted_packets.index([[2]]) + 1) * (sorted_packets.index([[6]]) + 1)
if __name__ == '__main__':
day = Day(2022, 13)
day.run(verbose=True)