Implement day 6 part 2

This commit is contained in:
Gabriel Augendre 2020-03-05 21:48:44 +01:00
parent 6a69ee4255
commit f633e19cea
No known key found for this signature in database
GPG key ID: 1E693F4CE4AEE7B4
2 changed files with 41 additions and 8 deletions

View file

@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Dict
from typing import Dict, List
@dataclass
@ -11,17 +11,38 @@ class Node:
return self.name.lower() == "com"
def count_hops(self):
counter = 0
return len(self.chain()) - 1 # Not counting self but it's part of the chain
def chain(self):
chain = [self]
current = self
while not current.is_origin():
current = current.orbits_over
counter += 1
return counter
chain.append(current)
return chain
def common_chain(self, other: "Node") -> List["Node"]:
chain = []
for el1, el2 in zip(reversed(self.chain()), reversed(other.chain())):
if el1 != el2:
break
chain.append(el1)
return chain
def __str__(self) -> str:
if self.orbits_over:
return f"{self.orbits_over.name}){self.name}"
else:
return self.name
def __eq__(self, other: "Node") -> bool:
return self.name == other.name
def main():
with open("inputs/day06") as f:
orbits = f.read().split()
objects = dict() # type: Dict[str, Node]
for orbit in orbits:
stator, rotor = orbit.split(")")
@ -31,11 +52,10 @@ def main():
objects[stator.name] = stator
objects[rotor.name] = rotor
counter = 0
for obj in objects.values():
counter += obj.count_hops()
me = objects["YOU"]
santa = objects["SAN"]
print(counter)
print(me.count_hops() + santa.count_hops() - 2 * len(me.common_chain(santa)))
if __name__ == "__main__":

13
2019/inputs/day06-ex2 Normal file
View file

@ -0,0 +1,13 @@
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN