Skip to content

Commit 4e99304

Browse files
committed
2022 - Day 13
1 parent fb4adea commit 4e99304

File tree

2 files changed

+520
-0
lines changed

2 files changed

+520
-0
lines changed

python/2022/day13/day13.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
from functools import cmp_to_key
2+
3+
from python.download_input import get_input_content
4+
5+
6+
def compare(left: str, rigth: str) -> int:
7+
left = eval(left)
8+
rigth = eval(rigth)
9+
10+
# Fix type mismatch
11+
if type(left) != type(rigth):
12+
if type(left) == int:
13+
left = [left]
14+
elif type(rigth) == int:
15+
rigth = [rigth]
16+
17+
if type(left) == int:
18+
return left - rigth
19+
20+
# Compare two lists
21+
i = 0
22+
while i < max(len(left), len(rigth)):
23+
try:
24+
left_value = left[i]
25+
except IndexError:
26+
# If the left list runs out of items first, the inputs are in the right order
27+
return -1
28+
try:
29+
rigth_value = rigth[i]
30+
except IndexError:
31+
# If the right list runs out of items first, the inputs are not in the right order
32+
return 1
33+
result = compare(str(left_value), str(rigth_value))
34+
if result != 0:
35+
return result
36+
i += 1
37+
return 0
38+
39+
40+
def first(data):
41+
data = data.split('\n\n')
42+
right_orders = []
43+
44+
for i, line in enumerate(data):
45+
left, rigth = line.split('\n')
46+
result = compare(left, rigth)
47+
if result < 0:
48+
right_orders.append(i+1)
49+
50+
return sum(right_orders)
51+
52+
53+
def second(data):
54+
# Remove blank lines
55+
data = data.replace('\n\n', '\n')
56+
# Add two packets
57+
data = '[[2]]\n[[6]]\n' + data
58+
# Split by line
59+
data = data.split('\n')
60+
# Sort with custom comparison
61+
data.sort(key=cmp_to_key(compare))
62+
63+
return (data.index('[[2]]') + 1) * (data.index('[[6]]') + 1)
64+
65+
66+
if __name__ == "__main__":
67+
content = get_input_content(__file__, split_by_lines=False)
68+
69+
print(f'Le résultat de la première partie est :\n{first(content)}')
70+
71+
print(f'Le résultat de la deuxième partie est :\n{second(content)}')

0 commit comments

Comments
 (0)