| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System.Collections.ObjectModel;
- using Day10;
- namespace Day11;
- public class Universe
- {
- public IList<Galaxy> Galaxies { get; } = new List<Galaxy>();
- public void Add(Galaxy galaxy)
- {
- Galaxies.Add(galaxy);
- }
- public void Expand(int expansionFactor)
- {
- var xMap = new Dictionary<long, IList<Galaxy>>();
- var yMap = new Dictionary<long, IList<Galaxy>>();
- foreach (var g in Galaxies)
- {
- if (!xMap.ContainsKey(g.Position.X))
- {
- xMap.Add(g.Position.X, new List<Galaxy>());
- }
- xMap[g.Position.X].Add(g);
- if (!yMap.ContainsKey(g.Position.Y))
- {
- yMap.Add(g.Position.Y, new List<Galaxy>());
- }
- yMap[g.Position.Y].Add(g);
- }
- var xPrev = -1L;
- var xExpand = 0L;
- foreach (var x in xMap.Keys.Order())
- {
- xExpand += x - xPrev - 1;
- xPrev = x;
-
- foreach (var g in xMap[x])
- {
- var delta = new GridPoint(xExpand * (expansionFactor - 1), 0);
- g.Move(delta);
- }
- }
-
- var yPrev = -1L;
- var yExpand = 0L;
- foreach (var y in yMap.Keys.Order())
- {
- yExpand += y - yPrev - 1;
- yPrev = y;
-
- foreach (var g in yMap[y])
- {
- var delta = new GridPoint(0, yExpand * (expansionFactor - 1));
- g.Move(delta);
- }
- }
- }
- public long GetTotalDistance()
- {
- var sum = 0L;
- foreach (var pair in BuildPairs())
- {
- var distance = pair.Left.Position.Distance(pair.Right.Position);
- Console.WriteLine($"{pair.Left.Id} <-> {pair.Right.Id} = {distance}");
- sum += distance;
- }
- return sum;
- }
- private IEnumerable<(Galaxy Left, Galaxy Right)> BuildPairs()
- {
- for (var i = 0; i < Galaxies.Count - 1; i++)
- {
- for (var j = i + 1; j < Galaxies.Count; j++)
- {
- yield return (Galaxies[i], Galaxies[j]);
- }
- }
- }
- }
|