From 5be719dcf971009b81cd2d19bf42d43a34045e33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Ytterstr=C3=B6m?= Date: Thu, 23 Nov 2023 12:10:01 +0100 Subject: [PATCH] Solve 2019:06 "Universal Orbit Map" Tried to solve part 2 using BFS, but did not figure out a way to find shortest path. Fell back to a less elegant but more simple approach. --- 2019-python/output/day_06.py | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 2019-python/output/day_06.py diff --git a/2019-python/output/day_06.py b/2019-python/output/day_06.py new file mode 100644 index 0000000..3d4f201 --- /dev/null +++ b/2019-python/output/day_06.py @@ -0,0 +1,46 @@ +from collections import defaultdict, deque +from output import answer, puzzleinput + +n = 6 +title = "Universal Orbit Map" + + +@puzzleinput(n) +def parse_input(data): + heritage = defaultdict(str) + for parent, child in [line.split(")") for line in data.split()]: + heritage[child] = parent + return heritage + + +@answer(1, "{} direct and indirect orbits") +def part_1(heritage): + return sum(len(ancestry(heritage, v)) for v in heritage.keys()) + + +@answer(2, "Orbit transfers needed for you to share orbit with Santa: {}") +def part_2(heritage): + a = ancestry(heritage, "YOU") + b = ancestry(heritage, "SAN") + shared = len(set(a) & set(b)) + return sum( + [ + len(a) - shared, + len(b) - shared, + ] + ) + + +def ancestry(parents, child): + k = child + lineage = [] + while k in parents: + lineage.append(parents[k]) + k = parents[k] + return lineage[::-1] + + +if __name__ == "__main__": + parsed = parse_input() + part_1(parsed) + part_2(parsed)