-
Notifications
You must be signed in to change notification settings - Fork 0
/
aoc18.py
executable file
·108 lines (85 loc) · 2.51 KB
/
aoc18.py
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env python3
import copy
import functools
import json
import itertools
import utils
import math
from dataclasses import dataclass
from typing import Tuple, List
@dataclass
class NodePointer:
value: object
index: int
level: int
_position: Tuple[List, int]
@property
def is_primitive(self):
return type(self.value) == int
@property
def is_regular(self):
return type(self.value) == list and all(type(v) == int for v in self.value)
def replace(self, new_value):
lst, idx = self._position
lst[idx] = new_value
def pointers(value, level=0, counter=None):
counter = counter or itertools.count()
for i, elem in enumerate(value):
yield NodePointer(elem, next(counter), level + 1, (value, i))
if type(elem) != int:
yield from pointers(elem, level + 1, counter)
def try_explode(value):
left_ptr = None
exploded_ptr = None
right_ptr = None
for ptr in pointers(value):
if exploded_ptr is None:
if ptr.is_primitive:
left_ptr = ptr
elif ptr.level == 4 and ptr.is_regular:
exploded_ptr = ptr
elif ptr.index > exploded_ptr.index + 2 and ptr.is_primitive:
right_ptr = ptr
break
if exploded_ptr:
a, b = exploded_ptr.value
if left_ptr:
left_ptr.replace(left_ptr.value + a)
if right_ptr:
right_ptr.replace(right_ptr.value + b)
exploded_ptr.replace(0)
return True
return False
def try_split(value):
for ptr in pointers(value):
if ptr.is_primitive and ptr.value >= 10:
value = ptr.value
ptr.replace([int(math.floor(value / 2)), int(math.ceil(value / 2))])
return True
return False
def sf_reduce(value):
while True:
if try_explode(value):
continue
if try_split(value):
continue
return
def sf_add(a, b):
result = [copy.deepcopy(a), copy.deepcopy(b)]
sf_reduce(result)
return result
def magnitude(elem):
if type(elem) == int:
return elem
else:
a, b = elem
return 3 * magnitude(a) + 2 * magnitude(b)
def main():
numbers = [json.loads(line.strip()) for line in utils.input()]
result = functools.reduce(sf_add, numbers)
print(result)
print(magnitude(result))
magnitudes = (magnitude(sf_add(a, b)) for a, b in itertools.permutations(numbers, 2))
print(max(magnitudes))
if __name__ == "__main__":
main()