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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import sys
from functools import cmp_to_key
infile = sys.argv[1] if len(sys.argv) > 1 else "data/13_2022.txt"
data = open(infile).read().strip()
lines = [x for x in data.split("\n")]
def compare(p1, p2):
if isinstance(p1, int) and isinstance(p2, int):
if p1 < p2:
return -1
elif p1 == p2:
return 0
else:
return 1
elif isinstance(p1, list) and isinstance(p2, list):
i = 0
while i < len(p1) and i < len(p2):
c = compare(p1[i], p2[i])
if c == -1:
return -1
if c == 1:
return 1
i += 1
if i == len(p1) and i < len(p2):
return -1
elif i == len(p2) and i < len(p1):
return 1
else:
return 0
elif isinstance(p1, int) and isinstance(p2, list):
return compare([p1], p2)
else:
return compare(p1, [p2])
packets = []
part1 = 0
for i, group in enumerate(data.split("\n\n")):
p1, p2 = group.split("\n")
p1 = eval(p1)
p2 = eval(p2)
packets.append(p1)
packets.append(p2)
if compare(p1, p2) == -1:
part1 += 1 + i
print(part1)
packets.append([[2]])
packets.append([[6]])
packets = sorted(packets, key=cmp_to_key(lambda p1, p2: compare(p1, p2)))
part2 = 1
for i, p in enumerate(packets):
if p == [[2]] or p == [[6]]:
part2 *= i + 1
print(part2)
|