12_1.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const util = require("util");
  2. const Vector3 = require("./Vector3");
  3. const Moon = require("./Moon");
  4. const input = parseInput([
  5. "<x=14, y=15, z=-2>",
  6. "<x=17, y=-3, z=4>",
  7. "<x=6, y=12, z=-13>",
  8. "<x=-2, y=10, z=-8>",
  9. ]);
  10. const tests = parseInput([
  11. "<x=-1, y=0, z=2>",
  12. "<x=2, y=-10, z=-7>",
  13. "<x=4, y=-8, z=8>",
  14. "<x=3, y=5, z=-1>",
  15. ]);
  16. /**
  17. * Find the gravitational influence two moons have on each other
  18. *
  19. * @param {Moon} moonA The first moon to consider
  20. * @param {Moon} moonB The second moon to consider
  21. *
  22. * @returns {Vector3} The gravitational influence of Moon B on Moon A
  23. */
  24. function calculateGravity(moonA, moonB) {
  25. // The gravitational pull on Moon A caused by Moon B
  26. const gravityDifference = new Vector3(
  27. // eslint-disable-next-line no-nested-ternary
  28. moonB.position.x > moonA.position.x ? 1 : (moonB.position.x < moonA.position.x ? -1 : 0),
  29. // eslint-disable-next-line no-nested-ternary
  30. moonB.position.y > moonA.position.y ? 1 : (moonB.position.y < moonA.position.y ? -1 : 0),
  31. // eslint-disable-next-line no-nested-ternary
  32. moonB.position.z > moonA.position.z ? 1 : (moonB.position.z < moonA.position.z ? -1 : 0),
  33. );
  34. return gravityDifference;
  35. }
  36. /**
  37. * @param {string[]} inputs The day's input
  38. * @returns {Moon[]} An array of Moon objects
  39. */
  40. function parseInput(inputs) {
  41. const moons = [];
  42. const parseRegex = new RegExp(/x=(-?\d+), y=(-?\d+), z=(-?\d+)/);
  43. for (const position of inputs) {
  44. // eslint-disable-next-line no-shadow-restricted-names
  45. const [undefined, x, y, z] = position.match(parseRegex);
  46. moons.push(new Moon(new Vector3(parseInt(x, 10), parseInt(y, 10), parseInt(z, 10))));
  47. }
  48. return moons;
  49. }
  50. // console.log(util.inspect(parseInput(input)));