public void ApplyGravity(Moon other) { if (other == this) { return; } if (x < other.x) { dX++; } else if (x > other.x) { dX--; } if (y < other.y) { dY++; } else if (y > other.y) { dY--; } if (z < other.z) { dZ++; } else if (z > other.z) { dZ--; } }
public override object Task1() { Moon[] moons = new Moon[input.Length]; for (int i = 0; i < input.Length; i++) { string[] parts = input[i].Substring(1, input[i].Length - 2).Split(", "); moons[i] = new Moon(int.Parse(parts[0].Split('=')[1]), int.Parse(parts[1].Split('=')[1]), int.Parse(parts[2].Split('=')[1])); } for (int _ = 0; _ < 1000; _++) { SimulateStep(moons); } long energy = 0; for (int i = 0; i < moons.Length; i++) { energy += NRG(moons[i].Position) * NRG(moons[i].Velocity); } return(energy); }
static Moon[] LoadMoons(string filename) { List <Moon> moons = new(); foreach (var line in FileIterator.Lines(filename)) { var groups = line.Groups(@"<x=([-\d]+), y=([-\d]+), z=([-\d]+)>"); var moon = new Moon(int.Parse(groups[0]), int.Parse(groups[1]), int.Parse(groups[2])); moons.Add(moon); } return(moons.ToArray()); }
private IList <Moon> ReadAndParse() { IList <string> lines = AdventUtils.ReadFileByLines(@"..\..\..\Files\Day12.txt"); IList <Moon> Moons = new List <Moon>(); foreach (string line in lines) { string[] cordinates = line.Split(','); Moon moon = new Moon(); moon.PosX = long.Parse(cordinates[0].Substring(cordinates[0].IndexOf('=') + 1)); moon.PosY = long.Parse(cordinates[1].Substring(cordinates[1].IndexOf('=') + 1)); moon.PosZ = long.Parse(cordinates[2].Substring(cordinates[2].IndexOf('=') + 1, cordinates[2].Length - 4)); Moons.Add(moon); } return(Moons); }
public override object Task2() { Moon[] moons = new Moon[input.Length]; for (int i = 0; i < input.Length; i++) { string[] parts = input[i].Substring(1, input[i].Length - 2).Split(", "); moons[i] = new Moon(int.Parse(parts[0].Split('=')[1]), int.Parse(parts[1].Split('=')[1]), int.Parse(parts[2].Split('=')[1])); } long[] intervals = new long[3]; int found = 0; for (int step = 1; found < 3; step++) { SimulateStep(moons); bool[] stopped = new bool[] { true, true, true }; for (int i = 0; i < moons.Length; i++) { stopped[0] &= moons[i].Velocity.X == 0; stopped[1] &= moons[i].Velocity.Y == 0; stopped[2] &= moons[i].Velocity.Z == 0; } for (int i = 0; i < intervals.Length; i++) { if (intervals[i] == 0 && stopped[i]) { intervals[i] = step * 2; found++; } } } return(LCM(intervals)); }