|
@@ -16,6 +16,36 @@ const tests = parseInput([
|
|
"<x=3, y=5, z=-1>",
|
|
"<x=3, y=5, z=-1>",
|
|
]);
|
|
]);
|
|
|
|
|
|
|
|
+const STEPS = 1000;
|
|
|
|
+
|
|
|
|
+for (let i = 0; i < STEPS; i++) {
|
|
|
|
+ step(input);
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+console.log(`Total energy in system is: ${calculateTotalEnergy(input)}`);
|
|
|
|
+
|
|
|
|
+/**
|
|
|
|
+ * Calculate one step of time
|
|
|
|
+ *
|
|
|
|
+ * @param {Moon[]} moons A list of moons
|
|
|
|
+ * @returns {void}
|
|
|
|
+ */
|
|
|
|
+function step(moons) {
|
|
|
|
+ for (let i = 0; i < moons.length - 1; i++) {
|
|
|
|
+ for (let j = i + 1; j < moons.length; j++) {
|
|
|
|
+ // Calculate Moon B's gravity influence on Moon A
|
|
|
|
+ const firstGravity = calculateGravity(moons[i], moons[j]);
|
|
|
|
+ // Invert the signage to represent Moon A's influence on Moon B
|
|
|
|
+ const secondGravity = firstGravity.negate();
|
|
|
|
+
|
|
|
|
+ moons[i].velocity.add(firstGravity);
|
|
|
|
+ moons[j].velocity.add(secondGravity);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ moons.forEach((moon) => { moon.position.add(moon.velocity); });
|
|
|
|
+}
|
|
|
|
+
|
|
/**
|
|
/**
|
|
* Find the gravitational influence two moons have on each other
|
|
* Find the gravitational influence two moons have on each other
|
|
*
|
|
*
|
|
@@ -38,6 +68,27 @@ function calculateGravity(moonA, moonB) {
|
|
return gravityDifference;
|
|
return gravityDifference;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
+/**
|
|
|
|
+ * Calculate the total energy in the system
|
|
|
|
+ *
|
|
|
|
+ * The total energy in the system is the sum of the sum of the positional
|
|
|
|
+ * values multiplied by the sum of the velocity values.
|
|
|
|
+ *
|
|
|
|
+ * @param {Moon[]} moons The moons in the system
|
|
|
|
+ * @returns {number} The total energy in the system
|
|
|
|
+ */
|
|
|
|
+function calculateTotalEnergy(moons) {
|
|
|
|
+ let energy = 0;
|
|
|
|
+
|
|
|
|
+ for (const moon of moons) {
|
|
|
|
+ const potentialEnergy = Math.abs(moon.position.x) + Math.abs(moon.position.y) + Math.abs(moon.position.z);
|
|
|
|
+ const kineticEnergy = Math.abs(moon.velocity.x) + Math.abs(moon.velocity.y) + Math.abs(moon.velocity.z);
|
|
|
|
+ energy += potentialEnergy * kineticEnergy;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ return energy;
|
|
|
|
+}
|
|
|
|
+
|
|
/**
|
|
/**
|
|
* @param {string[]} inputs The day's input
|
|
* @param {string[]} inputs The day's input
|
|
* @returns {Moon[]} An array of Moon objects
|
|
* @returns {Moon[]} An array of Moon objects
|