Created
December 6, 2019 20:15
-
-
Save sduvick/a6fd8e793e508bbb4389cb3ae17ec47d to your computer and use it in GitHub Desktop.
C# Recursive tree structure - Advent of Code 2019 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
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Linq; | |
using System.IO; | |
namespace Day06 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Part 1 | |
string[] input = File.ReadAllLines(@"input.txt"); | |
List<OrbitObj> objList = input.Select(x => new OrbitObj { Base = x.Split(')')[0], Outer = x.Split(')')[1] }).ToList(); | |
Dictionary<string, List<string>> steps = new Dictionary<string, System.Collections.Generic.List<string>>(); | |
foreach (string outer in objList.Select(x => x.Outer)) | |
{ | |
steps.Add(outer, TotalOrbits(outer, objList, new List<string>())); | |
} | |
Console.WriteLine(steps.Sum(x => x.Value.Count())); | |
//Part 2 | |
var santaSteps = TotalOrbits("SAN", objList, new List<string>()); | |
//steps from you down | |
var youSteps = TotalOrbits("YOU", objList, new List<string>()); | |
//find the first step in common | |
var matchStep = santaSteps.Intersect(youSteps).First(); | |
Console.WriteLine(santaSteps.IndexOf(matchStep) + youSteps.IndexOf(matchStep)); | |
} | |
public static List<string> TotalOrbits(string outer, List<OrbitObj> allOrbits, List<string> currSteps) | |
{ | |
if (outer == "COM") | |
{ | |
return currSteps; | |
} | |
string currBase = allOrbits.Single(x => x.Outer == outer).Base; | |
currSteps.Add(currBase); | |
return TotalOrbits(currBase, allOrbits, currSteps); | |
} | |
} | |
public class OrbitObj | |
{ | |
public string Base { get; set; } | |
public string Outer { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment