Advertisement
scibuff

Advent of Code 2023 - Day 21 - Part 2

Dec 21st, 2023
1,164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.73 KB | Source Code | 0 0
  1. /**
  2.  * Lagrange's Interpolation formula for ax^2 + bx + c with x=[0,1,2] and y=[y0,y1,y2] we have
  3.  *   f(x) = (x^2-3x+2) * y0/2 - (x^2-2x)*y1 + (x^2-x) * y2/2
  4.  * so the coefficients are:
  5.  * a = y0/2 - y1 + y2/2
  6.  * b = -3*y0/2 + 2*y1 - y2/2
  7.  * c = y0
  8.  */
  9. const simplifiedLagrange = (values) => {
  10.   return {
  11.     a: values[0] / 2 - values[1] + values[2] / 2,
  12.     b: -3 * (values[0] / 2) + 2 * values[1] - values[2] / 2,
  13.     c: values[0],
  14.   };
  15. };
  16. const solvePart2 = (input) => {
  17.   const values = [solvePart1(input, 65), solvePart1(input, 65 + 131), solvePart1(input, 65 + 131 * 2)];
  18.   const poly = simplifiedLagrange(values);
  19.   const target = (26_501_365 - 65) / 131;
  20.   return poly.a * target * target + poly.b * target + poly.c;
  21. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement