12_1.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. const Moon = require("./Moon");
  2. const { step, parseInput } = require("./common");
  3. const input = parseInput([
  4. "<x=14, y=15, z=-2>",
  5. "<x=17, y=-3, z=4>",
  6. "<x=6, y=12, z=-13>",
  7. "<x=-2, y=10, z=-8>",
  8. ]);
  9. const tests = parseInput([
  10. "<x=-1, y=0, z=2>",
  11. "<x=2, y=-10, z=-7>",
  12. "<x=4, y=-8, z=8>",
  13. "<x=3, y=5, z=-1>",
  14. ]);
  15. const STEPS = 1000;
  16. for (let i = 0; i < STEPS; i++) {
  17. step(input);
  18. }
  19. console.log(`Total energy in system is: ${calculateTotalEnergy(input)}`);
  20. /**
  21. * Calculate the total energy in the system
  22. *
  23. * The total energy in the system is the sum of the sum of the positional
  24. * values multiplied by the sum of the velocity values.
  25. *
  26. * @param {Moon[]} moons The moons in the system
  27. * @returns {number} The total energy in the system
  28. */
  29. function calculateTotalEnergy(moons) {
  30. let energy = 0;
  31. for (const moon of moons) {
  32. const potentialEnergy = Math.abs(moon.position.x) + Math.abs(moon.position.y) + Math.abs(moon.position.z);
  33. const kineticEnergy = Math.abs(moon.velocity.x) + Math.abs(moon.velocity.y) + Math.abs(moon.velocity.z);
  34. energy += potentialEnergy * kineticEnergy;
  35. }
  36. return energy;
  37. }