diff --git a/AdventOfCode/Day23.cs b/AdventOfCode/Day23.cs index 23f8b59..a91b890 100644 --- a/AdventOfCode/Day23.cs +++ b/AdventOfCode/Day23.cs @@ -1,34 +1,14 @@ -namespace AdventOfCode; +using System.Text.RegularExpressions; + +namespace AdventOfCode; public class Day23 : BaseDay { public override ValueTask Solve_1() { string[] lines = File.ReadAllLines(InputFilePath); - - HashSet groups = new HashSet(); Dictionary> dictionary = ToDictionary(lines); - - foreach (var kv in dictionary) - { - string computer1 = kv.Key; - if (kv.Value.Count < 2) - { - continue; - } - for (int i = 0; i < kv.Value.Count - 1; ++i) - { - for (int j = i + 1; j < kv.Value.Count; ++j) - { - if (dictionary[kv.Value[i]].Contains(kv.Value[j])) - { - var group = new List { computer1, kv.Value[i], kv.Value[j] }; - group = group.OrderBy(x => x).ToList(); - groups.Add($"{group[0]},{group[1]},{group[2]}"); - } - } - } - } + HashSet groups = GetSetsOfThree(lines, dictionary); int res = groups.Count(g => g.Split(",").Any(x => x.StartsWith("t"))); @@ -37,7 +17,17 @@ public override ValueTask Solve_1() public override ValueTask Solve_2() { - return new (""); + string[] lines = File.ReadAllLines(InputFilePath); + Dictionary> dictionary = ToDictionary(lines); + HashSet groups = GetSetsOfThree(lines, dictionary); + + while (groups.Count != 1) + { + groups = GetGroupsPlusOne(groups, dictionary); + Console.WriteLine(groups.Count); + } + + return new (groups.Single().ToString()); } private Dictionary> ToDictionary(string[] lines) @@ -61,4 +51,56 @@ private Dictionary> ToDictionary(string[] lines) return result; } + + private HashSet GetSetsOfThree(string[] lines, Dictionary> dictionary) + { + HashSet groups = new HashSet(); + + foreach (var kv in dictionary) + { + string computer1 = kv.Key; + if (kv.Value.Count < 2) + { + continue; + } + for (int i = 0; i < kv.Value.Count - 1; ++i) + { + for (int j = i + 1; j < kv.Value.Count; ++j) + { + if (dictionary[kv.Value[i]].Contains(kv.Value[j])) + { + var group = new List { computer1, kv.Value[i], kv.Value[j] }; + group = group.OrderBy(x => x).ToList(); + groups.Add($"{group[0]},{group[1]},{group[2]}"); + } + } + } + } + return groups; + } + + private HashSet GetGroupsPlusOne(HashSet groups, Dictionary> dictionary) + { + HashSet groupsPlusOne = new HashSet(); + foreach (var group in groups) + { + List computers = group.Split(",").ToList(); + foreach (var computer in dictionary.Keys) + { + if (computers.Contains(computer)) + { + continue; + } + int intersect = dictionary[computer].Intersect(computers).Count(); + if (intersect == computers.Count) + { + var newGroup = computers.Concat(new List { computer }); + newGroup = newGroup.OrderBy(x => x).ToList(); + groupsPlusOne.Add(string.Join(",", newGroup)); + } + } + } + + return groupsPlusOne; + } }