9_1.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { SumArray, ArrayIsOnlyDuplicates, LoadInput } from "../common.ts";
  2. import { FindDifferential, ParseInput, type Histogram } from "./9_common.ts";
  3. const tests = [
  4. "0 3 6 9 12 15",
  5. "1 3 6 10 15 21",
  6. "10 13 16 21 30 45",
  7. ];
  8. const input = await LoadInput(9);
  9. // Parse the histograms from the input
  10. let histograms = ParseInput(input);
  11. // Find the next predicted value for each one
  12. histograms = histograms.map((histogram, idx) => {
  13. try {
  14. return PredictNextValue(histogram);
  15. } catch (err) {
  16. console.error(`Failed on histogram[${idx}]`);
  17. throw err;
  18. }
  19. });
  20. // Sum all of the last values in the histograms
  21. const sumOfNewValues = SumArray(histograms.map((histogram) => histogram[histogram.length - 1]));
  22. console.log(`The sum of all predicted values is: ${sumOfNewValues}`);
  23. /**
  24. * Predict the next value in a histogram
  25. *
  26. * @param histogram The histogram to find the next value for
  27. * @returns The input histogram with its new value added
  28. */
  29. function PredictNextValue(histogram: Histogram): Histogram {
  30. const allDifferentials = [histogram];
  31. let differential = [];
  32. // Get all differentials until only an array of zeros remains
  33. do {
  34. differential = FindDifferential(allDifferentials[0]);
  35. allDifferentials.unshift(differential);
  36. } while (!ArrayIsOnlyDuplicates(differential));
  37. while (allDifferentials.length > 1) {
  38. // Store the last value of previous differential, and remove that differential from the list
  39. const lastValueOfDifferential = allDifferentials.shift()?.pop() as number;
  40. // if (lastValueOfDifferential == undefined) {
  41. // throw new Error("There is no last value of previous differential!\n" + prevDifferential);
  42. // }
  43. // Store the last index of the current differential for easier reading
  44. const lastIndexOfDifferential = allDifferentials[0].length - 1;
  45. // if (lastIndexOfDifferential < 0) {
  46. // throw new Error("There is no last index of the current differential");
  47. // }
  48. // Predict the next value to be this last value + the last value of the previous differential
  49. const predictedValue = allDifferentials[0][lastIndexOfDifferential] + lastValueOfDifferential;
  50. if (Number.isNaN(predictedValue)) {
  51. throw new Error("Failed to find differentials for the following histograms!\n" + histogram);
  52. }
  53. // Push to this differential
  54. allDifferentials[0].push(predictedValue);
  55. }
  56. return allDifferentials[0];
  57. }