day18: there must be a better way to find left and right numbers instead of traversing the full tree again and again ...
This commit is contained in:
parent
81bef8d2bf
commit
0ef34d1a32
30
day18.py
30
day18.py
@ -115,8 +115,21 @@ class BinarySnailfish:
|
||||
return root
|
||||
|
||||
def getLeftNumber(self) -> Union[None, 'BinarySnailfish']:
|
||||
parent = self.parent
|
||||
if self == self.parent.left:
|
||||
while parent.parent and parent == parent.parent.left:
|
||||
parent = parent.parent
|
||||
parent = parent.left
|
||||
else:
|
||||
while parent.parent and parent == parent.parent.right:
|
||||
parent = parent.parent
|
||||
parent = parent.right
|
||||
while parent.right.value is None:
|
||||
parent = parent.right
|
||||
return parent
|
||||
|
||||
leftnum = None
|
||||
for current in self.getRoot().traverse_inorder():
|
||||
for current in self.getRoot().traverse_preorder():
|
||||
if current == self:
|
||||
return leftnum
|
||||
if current.value is not None:
|
||||
@ -124,7 +137,7 @@ class BinarySnailfish:
|
||||
|
||||
def getRightNumber(self) -> Union[None, 'BinarySnailfish']:
|
||||
returnNext = 0
|
||||
for current in self.getRoot().traverse_inorder():
|
||||
for current in self.getRoot().traverse_preorder():
|
||||
if returnNext >= 3 and current.value is not None:
|
||||
return current
|
||||
if returnNext > 0:
|
||||
@ -150,14 +163,13 @@ class BinarySnailfish:
|
||||
self.value = 0
|
||||
|
||||
def reduce(self):
|
||||
print(self.fours)
|
||||
if self.value is not None:
|
||||
return
|
||||
found = True
|
||||
while found:
|
||||
found = False
|
||||
for n in self.fours:
|
||||
self.fours.pop(0)
|
||||
for n in self.traverse_preorder():
|
||||
if n.value is None and n.depth == 4:
|
||||
n.explode()
|
||||
found = True
|
||||
break
|
||||
@ -165,21 +177,21 @@ class BinarySnailfish:
|
||||
if found:
|
||||
continue
|
||||
|
||||
for n in self.traverse_inorder():
|
||||
for n in self.traverse_preorder():
|
||||
if n.value is not None and n.value > 9:
|
||||
n.split()
|
||||
found = True
|
||||
break
|
||||
|
||||
def traverse_inorder(self):
|
||||
def traverse_preorder(self):
|
||||
yield self
|
||||
|
||||
if self.left:
|
||||
for x in self.left.traverse_inorder():
|
||||
for x in self.left.traverse_preorder():
|
||||
yield x
|
||||
|
||||
if self.right:
|
||||
for x in self.right.traverse_inorder():
|
||||
for x in self.right.traverse_preorder():
|
||||
yield x
|
||||
|
||||
def __add__(self, other):
|
||||
|
||||
Loading…
Reference in New Issue
Block a user