-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday06b.py
62 lines (46 loc) · 1.46 KB
/
day06b.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class SpaceObject:
def __init__(self, name):
self.name = name
self.orbits = None
self.orbited_by = []
space_objects = {'COM': SpaceObject('COM')}
def main():
with open('day06_input.txt') as file:
for line in file:
process_orbit(line.strip())
# Start from the object YOU is orbiting
curr = space_objects['YOU'].orbits
steps = 0
while curr.name != 'SAN':
if contains_san(curr):
for child in curr.orbited_by:
if contains_san(child):
curr = child
steps += 1
break
else:
curr = curr.orbits
steps += 1
print(steps - 1)
def contains_san(space_object):
# Fully traverse space_object and orbiting objects searching for SAN
traversal_list = [space_object]
while traversal_list:
obj = traversal_list.pop()
if obj.name == 'SAN':
return True
else:
traversal_list += obj.orbited_by
else:
return False
def process_orbit(orbit):
orbited_name = orbit[:3]
orbiting_name = orbit[4:]
# Lookup or add from dictionary
orbited = space_objects.setdefault(orbited_name, SpaceObject(orbited_name))
orbiting = space_objects.setdefault(orbiting_name, SpaceObject(orbiting_name))
# Update the relationships
orbited.orbited_by.append(orbiting)
orbiting.orbits = orbited
if __name__ == '__main__':
main()