Created
December 6, 2019 17:49
-
-
Save zer0tonin/e381061386d110aa4109d8da73cb1707 to your computer and use it in GitHub Desktop.
Advent of Code day 6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, value): | |
self.value = value | |
self.adjacent = [] | |
def is_santa(self): | |
return self.value == "SAN" | |
def is_you(self): | |
return self.value == "YOU" | |
def add_adjacent(self, child): | |
self.adjacent.append(child) | |
class Graph: | |
def __init__(self, root): | |
self.root = root | |
self.distance = 0 | |
def count_orbits(self): | |
visited = set() | |
def recurse(node, counter): | |
visited.add(node) | |
adjacent = [n for n in node.adjacent if n not in visited] | |
if not adjacent: | |
return None | |
for n in adjacent: | |
if n.is_santa(): | |
return counter | |
results = [recurse(child, counter + 1) for child in adjacent] | |
results = [result for result in results if result is not None] | |
if results: | |
return min(results) | |
return None | |
return recurse(self.root, 0) | |
def parse_graph(input_filename): | |
node_map = {} | |
with open(input_filename) as stream: | |
line = stream.readline() | |
while line: | |
node_tuple = line.strip().split(')') | |
if node_map.get(node_tuple[0]) is None: | |
node_map[node_tuple[0]] = Node(node_tuple[0]) | |
parent = node_map[node_tuple[0]] | |
if node_map.get(node_tuple[1]) is None: | |
node_map[node_tuple[1]] = Node(node_tuple[1]) | |
child = node_map[node_tuple[1]] | |
parent.add_adjacent(child) | |
child.add_adjacent(parent) | |
line = stream.readline() | |
for node in node_map.values(): | |
if node.is_you(): | |
return Graph(node) | |
assert parse_graph("input_test2").count_orbits() == 5 | |
print("santa_distance ok") | |
print(parse_graph("input").count_orbits()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment