12_1.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const util = require("util");
  2. const input = [
  3. "<x=14, y=15, z=-2>",
  4. "<x=17, y=-3, z=4>",
  5. "<x=6, y=12, z=-13>",
  6. "<x=-2, y=10, z=-8>",
  7. ];
  8. class Vector3 {
  9. /**
  10. * A 3D vector
  11. *
  12. * @param {number} x The X value of this vector
  13. * @param {number} y The Y value of this vector
  14. * @param {number} z The Z value of this vector
  15. */
  16. constructor(x, y, z) {
  17. this.x = x;
  18. this.y = y;
  19. this.z = z;
  20. }
  21. /**
  22. * Add another vector to this one
  23. *
  24. * @param {Vector3} operand The vector to add to this one
  25. * @returns {void}
  26. */
  27. add(operand) {
  28. this.x += operand.x;
  29. this.y += operand.y;
  30. this.z += operand.z;
  31. }
  32. }
  33. /**
  34. * Find the gravitational influence two moons have on each other
  35. *
  36. * @param {Vector3} moonA The first moon to consider
  37. * @param {Vector3} moonB The second moon to consider
  38. *
  39. * @returns {void}
  40. */
  41. function calculateGravity(moonA, moonB) {
  42. // The gravitational pull on Moon A caused by Moon B
  43. const gravityA = new Vector3(
  44. // eslint-disable-next-line no-nested-ternary
  45. moonB.x > moonA.x ? 1 : (moonB.x < moonA.x ? -1 : 0),
  46. // eslint-disable-next-line no-nested-ternary
  47. moonB.y > moonA.y ? 1 : (moonB.y < moonA.y ? -1 : 0),
  48. // eslint-disable-next-line no-nested-ternary
  49. moonB.z > moonA.z ? 1 : (moonB.z < moonA.z ? -1 : 0),
  50. );
  51. }
  52. /**
  53. * @param {string[]} inputs The day's input
  54. * @returns {Vector3[]} An array of Vector3's representing the positions of moons
  55. */
  56. function parseInput(inputs) {
  57. const moons = [];
  58. const parseRegex = new RegExp(/x=(-?\d+), y=(-?\d+), z=(-?\d+)/);
  59. for (const position of inputs) {
  60. // eslint-disable-next-line no-shadow-restricted-names
  61. const [undefined, x, y, z] = position.match(parseRegex);
  62. moons.push(new Vector3(parseInt(x, 10), parseInt(y, 10), parseInt(z, 10)));
  63. }
  64. return moons;
  65. }
  66. console.log(util.inspect(parseInput(input)));