public async ValueTask <long> GetPart2() { // Setup moons in first position with 0 velocity var moons = initialPositions.Select(x => new Moon() { Position = x }).ToArray(); var xes = initialPositions.Select(p => p.x).ToArray(); var yes = initialPositions.Select(p => p.y).ToArray(); var zes = initialPositions.Select(p => p.z).ToArray(); var linked = new MoonWithInfluencingBodies[moons.Length]; for (var i = 0; i < moons.Length; i++) { var related = new List <Moon>(moons); related.Remove(moons[i]); linked[i] = new(moons[i], related.ToArray()); } // Iterate system until all axes have reset at least once long equalX = 0, equalY = 0, equalZ = 0, round = 0; while (equalX == 0 || equalY == 0 || equalZ == 0) { MoveOneStep(linked); round++; if (equalX == 0 && moons.Select(m => m.Position.x).SequenceEqual(xes) && moons.All(m => m.Velocity.x == 0)) { equalX = round; } if (equalY == 0 && moons.Select(m => m.Position.y).SequenceEqual(yes) && moons.All(m => m.Velocity.y == 0)) { equalY = round; } if (equalZ == 0 && moons.Select(m => m.Position.z).SequenceEqual(zes) && moons.All(m => m.Velocity.z == 0)) { equalZ = round; } } // then find the first iteration where all 3 are reset var sorted = new long[] { equalX, equalY, equalZ }.OrderByDescending(x => x).ToList(); return(LeastCommonMultiple(LeastCommonMultiple(sorted[0], sorted[1]), sorted[2])); }
public async ValueTask <long> GetPart1() { // Setup moons in first position with 0 velocity var moons = initialPositions.Select(x => new Moon() { Position = x }).ToArray(); var linked = new MoonWithInfluencingBodies[moons.Length]; for (var i = 0; i < moons.Length; i++) { var related = new List <Moon>(moons); related.Remove(moons[i]); linked[i] = new(moons[i], related.ToArray()); } for (var i = 1; i <= 1_000; i++) { MoveOneStep(linked); } return(moons.Sum(x => x.GetEnergy())); }