day18: start implementing binary tree solution

This commit is contained in:
Stefan Harmuth 2021-12-20 08:56:23 +01:00
parent 44148fd4ae
commit 16f5e881fe

View File

@ -1,9 +1,9 @@
import json
import re import re
from itertools import combinations from itertools import combinations
from math import ceil from math import ceil
from tools.aoc import AOCDay from tools.aoc import AOCDay
from typing import Any from typing import Any, List, Union
re_pair = re.compile(r"\[(\d+),(\d+)\]") re_pair = re.compile(r"\[(\d+),(\d+)\]")
re_lnum = re.compile(r".*[^\d](\d+)") re_lnum = re.compile(r".*[^\d](\d+)")
@ -72,12 +72,59 @@ class Snailfish:
return int(pairs) return int(pairs)
class BinarySnailfish:
def __init__(self, value: Union[int, List] = None, depth: int = 0):
self.depth = depth
if not isinstance(value, list):
self.value = value
self.left = None
self.right = None
else:
self.value = None
if isinstance(value[0], BinarySnailfish):
self.left = value[0]
self.left.incDepth()
else:
self.left = BinarySnailfish(value[0])
if isinstance(value[1], BinarySnailfish):
self.right = value[1]
self.right.incDepth()
else:
self.right = BinarySnailfish(value[1])
while reduce(self):
pass
def incDepth(self):
self.depth += 1
if self.value:
return
else:
self.left.incDepth()
self.right.incDepth()
def __add__(self, other):
return BinarySnailfish([self, other])
def getMagnitude(self):
if self.value:
return self.value
else:
return self.left.getMagnitude() * 3 + self.right.getMagnitude() * 2
def reduce(node: BinarySnailfish):
pass
class Day(AOCDay): class Day(AOCDay):
test_solutions_p1 = [4140, 4417] test_solutions_p1 = [4140, 4417]
test_solutions_p2 = [3993, 4796] test_solutions_p2 = [3993, 4796]
def part1(self) -> Any: def part1(self) -> Any:
snailfishes = [Snailfish(x) for x in self.getInput()] #snailfishes = [Snailfish(x) for x in self.getInput()]
snailfishes = [BinarySnailfish(json.loads(x)) for x in self.getInput()]
return sum(snailfishes[1:], start=snailfishes[0]).getMagnitude() return sum(snailfishes[1:], start=snailfishes[0]).getMagnitude()
def part2(self) -> Any: def part2(self) -> Any: