protected static void ListConnectedPrograms(ProgramUnit root, List <ProgramUnit> linkList) { if (!linkList.Contains(root)) { linkList.Add(root); foreach (ProgramUnit program in root.linkedPrograms) { ListConnectedPrograms(program, linkList); } } }
static void Main(string[] args) { string[] input; string line; string[] delimiter = { " ", "\t", ",", "<->" }; string filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory); List <ProgramUnit> programs = new List <ProgramUnit>(); Dictionary <string, ProgramUnit> programLookup = new Dictionary <string, ProgramUnit>(); // Read the puzzle input. StreamReader file = new StreamReader(filePath + "/input.txt"); while ((line = file.ReadLine()) != null) { input = line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); ProgramUnit program = new ProgramUnit(input[0]); programs.Add(program); programLookup.Add(input[0], program); } file.Dispose(); // Re-read the input file = new StreamReader(filePath + "/input.txt"); while ((line = file.ReadLine()) != null) { input = line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); ProgramUnit program = programLookup[input[0]]; for (int i = 1; i < input.Length; i++) { program.linkedPrograms.Add(programLookup[input[i]]); } } file.Dispose(); List <ProgramUnit> linkedPrograms = new List <ProgramUnit>(); ListConnectedPrograms(programLookup["0"], linkedPrograms); Console.WriteLine(programLookup.Count); Console.WriteLine(programs.Count); Console.WriteLine("Part 1: Programs connected to '0': " + linkedPrograms.Count); Console.ReadKey(); int groups = 1; // Part 2. while (programs.Count > 0) { foreach (ProgramUnit program in linkedPrograms) { programs.Remove(program); } linkedPrograms.Clear(); if (programs.Count > 0) { ListConnectedPrograms(programs[0], linkedPrograms); groups++; } } Console.WriteLine("Part 2: Number of program groups: " + groups); Console.ReadKey(); }