mgla

Advent of Code - 2025 - Day 8

Dec 8th, 2025 (edited)
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. var input = await File.ReadAllLinesAsync("input.txt");
  2.  
  3. var junctionBoxes = input
  4.     .Select(line => line.Split(','))
  5.     .Select(parts => new JunctionBox(long.Parse(parts[0]), long.Parse(parts[1]), long.Parse(parts[2])))
  6.     .ToList();
  7.  
  8. var distances = new List<(JunctionBox From, JunctionBox To, long Distance)>();
  9.  
  10. for (var i = 0; i < junctionBoxes.Count - 1; i++)
  11. {
  12.     var boxA = junctionBoxes[i];    
  13.  
  14.     for (var j = i + 1; j < junctionBoxes.Count; j++)
  15.     {
  16.         var boxB = junctionBoxes[j];
  17.         distances.Add((boxA, boxB, boxA.DistanceTo(boxB)));
  18.     }
  19. }
  20.  
  21. distances = [.. distances.OrderBy(d => d.Distance)];
  22.  
  23. var circuits = new List<HashSet<JunctionBox>>();
  24.  
  25. foreach (var box in junctionBoxes)
  26. {
  27.     circuits.Add([box]);
  28. }
  29.  
  30. var iteration = 0;
  31.  
  32. while (true)
  33. {
  34.     iteration++;
  35.  
  36.     var (from, to, _) = distances[iteration - 1];
  37.     var circuitA = circuits.First(c => c.Contains(from));
  38.     var circuitB = circuits.First(c => c.Contains(to));
  39.  
  40.     if (circuitA != circuitB)
  41.     {
  42.         circuitA.UnionWith(circuitB);
  43.         circuits.Remove(circuitB);
  44.         circuits = [.. circuits.OrderByDescending(c => c.Count)];
  45.     }    
  46.  
  47.     if (iteration == 1000)
  48.     {
  49.         Console.WriteLine($"Part 1: {circuits[0].Count * circuits[1].Count * circuits[2].Count}");
  50.     }
  51.  
  52.     if (circuits.All(c => c.Count > 1))
  53.     {
  54.         Console.WriteLine($"Part 2: {from.X * to.X}");
  55.         break;
  56.     }
  57. }
  58.  
  59. record struct JunctionBox(long X, long Y, long Z)
  60. {
  61.     public readonly long DistanceTo(JunctionBox other) =>
  62.         (long)Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2) + Math.Pow(Z - other.Z, 2));
  63. }
Advertisement
Add Comment
Please, Sign In to add comment