01020304050607080910111213141516171819202122232425

Advent of Code

2019/6

Universal Orbit Map

in C#

by encse

You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often involves transferring between orbits, the orbit maps here are useful for finding efficient routes between, for example, you and Santa. You download a map of the local orbits (your puzzle input).

Except for the universal Center of Mass (COM), every object in space is in orbit around exactly one other object. An orbit looks roughly like this:

Read the full puzzle.

using System.Collections.Generic;
using System.Linq;
using ChildToParent = System.Collections.Generic.Dictionary<string, string>;

namespace AdventOfCode.Y2019.Day06;

[ProblemName("Universal Orbit Map")]
class Solution : Solver {

    public object PartOne(string input) {
        var childToParent = ParseTree(input);
        return (
            from node in childToParent.Keys
            select GetAncestors(childToParent, node).Count()
        ).Sum();
    }

    public object PartTwo(string input) {
        var childToParent = ParseTree(input);
        var ancestors1 = new Stack<string>(GetAncestors(childToParent, "YOU"));
        var ancestors2 = new Stack<string>(GetAncestors(childToParent, "SAN"));
        while (ancestors1.Peek() == ancestors2.Peek()) {
            ancestors1.Pop();
            ancestors2.Pop();
        }
        return ancestors1.Count + ancestors2.Count;
    }

    ChildToParent ParseTree(string input) =>
        input
            .Split("\n")
            .Select(line => line.Split(")"))
            .ToDictionary(
                parent_child => parent_child[1],
                parent_child => parent_child[0]
            );

    IEnumerable<string> GetAncestors(ChildToParent childToParent, string node) {
        for (
            var parent = childToParent[node];
            parent != null;
            parent = childToParent.GetValueOrDefault(parent, null)
        ) {
            yield return parent;
        }

    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator