-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram_PartB.cs
More file actions
99 lines (80 loc) · 2.73 KB
/
Copy pathProgram_PartB.cs
File metadata and controls
99 lines (80 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.IO;
using System.Linq;
namespace Day__12
{
internal class Moon
{
public int X;
public int Y;
public int Z;
public int vX;
public int vY;
public int vZ;
public Moon(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
private static int A(int n) => Math.Abs(n);
public int KineticEnergy => A(X) + A(Y) + A(Z);
public int PotentialEnergy => A(vX) + A(vY) + A(vZ);
public int TotalEnergy => KineticEnergy * PotentialEnergy;
public static Moon Parse(string input)
{
var split = input.Split(',').Select(x => new string(x.Where(y => char.IsNumber(y) || y == '-').ToArray())).Select(int.Parse).ToArray();
return new Moon(split[0], split[1], split[2]);
}
}
internal class Program
{
private static void Main()
{
var moons = File.ReadAllLines("input3").Select(Moon.Parse).ToArray();
long steps = 0;
long xCycle = -1;
long yCycle = -1;
long zCycle = -1;
while (true)
{
foreach (var moon in moons)
{
foreach (var otherMoon in moons.Where(x => x != moon))
{
var deltaX = Math.Sign(otherMoon.X - moon.X);
var deltaY = Math.Sign(otherMoon.Y - moon.Y);
var deltaZ = Math.Sign(otherMoon.Z - moon.Z);
moon.vX += deltaX;
moon.vY += deltaY;
moon.vZ += deltaZ;
}
}
foreach (var moon in moons)
{
moon.X += moon.vX;
moon.Y += moon.vY;
moon.Z += moon.vZ;
}
steps++;
if (steps == 1000)
{
Console.WriteLine("Total energy:");
Console.WriteLine(moons.Sum(x => x.TotalEnergy));
}
if (xCycle == -1 && moons.All(x => x.vX == 0))
xCycle = steps;
if (yCycle == -1 && moons.All(x => x.vY == 0))
yCycle = steps;
if (zCycle == -1 && moons.All(x => x.vZ == 0))
zCycle = steps;
if (xCycle > -1 && yCycle > -1 && zCycle > -1)
{
Console.WriteLine("Cycle period:");
Console.WriteLine(MathNet.Numerics.Euclid.LeastCommonMultiple(new[] { xCycle, yCycle, zCycle }) * 2);
break;
}
}
}
}
}