Universe.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections.ObjectModel;
  2. using Day10;
  3. namespace Day11;
  4. public class Universe
  5. {
  6. public IList<Galaxy> Galaxies { get; } = new List<Galaxy>();
  7. public void Add(Galaxy galaxy)
  8. {
  9. Galaxies.Add(galaxy);
  10. }
  11. public void Expand(int expansionFactor)
  12. {
  13. var xMap = new Dictionary<long, IList<Galaxy>>();
  14. var yMap = new Dictionary<long, IList<Galaxy>>();
  15. foreach (var g in Galaxies)
  16. {
  17. if (!xMap.ContainsKey(g.Position.X))
  18. {
  19. xMap.Add(g.Position.X, new List<Galaxy>());
  20. }
  21. xMap[g.Position.X].Add(g);
  22. if (!yMap.ContainsKey(g.Position.Y))
  23. {
  24. yMap.Add(g.Position.Y, new List<Galaxy>());
  25. }
  26. yMap[g.Position.Y].Add(g);
  27. }
  28. var xPrev = -1L;
  29. var xExpand = 0L;
  30. foreach (var x in xMap.Keys.Order())
  31. {
  32. xExpand += x - xPrev - 1;
  33. xPrev = x;
  34. foreach (var g in xMap[x])
  35. {
  36. var delta = new GridPoint(xExpand * (expansionFactor - 1), 0);
  37. g.Move(delta);
  38. }
  39. }
  40. var yPrev = -1L;
  41. var yExpand = 0L;
  42. foreach (var y in yMap.Keys.Order())
  43. {
  44. yExpand += y - yPrev - 1;
  45. yPrev = y;
  46. foreach (var g in yMap[y])
  47. {
  48. var delta = new GridPoint(0, yExpand * (expansionFactor - 1));
  49. g.Move(delta);
  50. }
  51. }
  52. }
  53. public long GetTotalDistance()
  54. {
  55. var sum = 0L;
  56. foreach (var pair in BuildPairs())
  57. {
  58. var distance = pair.Left.Position.Distance(pair.Right.Position);
  59. Console.WriteLine($"{pair.Left.Id} <-> {pair.Right.Id} = {distance}");
  60. sum += distance;
  61. }
  62. return sum;
  63. }
  64. private IEnumerable<(Galaxy Left, Galaxy Right)> BuildPairs()
  65. {
  66. for (var i = 0; i < Galaxies.Count - 1; i++)
  67. {
  68. for (var j = i + 1; j < Galaxies.Count; j++)
  69. {
  70. yield return (Galaxies[i], Galaxies[j]);
  71. }
  72. }
  73. }
  74. }