2018-12-08 - Memory Maneuver
(original .ipynb)test_input = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2" # A---------------------------------- # B----------- C----------- # D----- real_input = open("puzzle_input/day8.txt").read()
class Node(object): def __init__(self, raw_input): num_children = raw_input.pop(0) num_metadata = raw_input.pop(0) self.children = [] for i in range(num_children): self.parse_child(raw_input) self.metadata = [] for i in range(num_metadata): self.parse_metadata(raw_input) def parse_child(self, raw_input): self.children.append(Node(raw_input)) def parse_metadata(self, raw_input): self.metadata.append(raw_input.pop(0)) def sum_metadata(self): return sum(self.metadata) + sum([ child.sum_metadata() for child in self.children]) def calculate_value(self): if not self.children: return sum(self.metadata) else: relevant_indices = [ i - 1 for i in self.metadata if 0 < i and i <= len(self.children)] return sum([ self.children[i].calculate_value() for i in relevant_indices ]) def parse(raw_input_string): raw_input_list = [ int(str) for str in raw_input_string.split(" ") ] return Node(raw_input_list) # Part 1 root = parse(real_input) print("part one:", root.sum_metadata()) # Part 2 print("part two:", root.calculate_value())
part one: 42196 part two: 33649