9_2.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { SumArray, ArrayIsOnlyDuplicates, LoadInput, Inspect } 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. Inspect(histograms);
  21. // Sum all of the last values in the histograms
  22. const sumOfNewValues = SumArray(histograms.map((histogram) => histogram[0]));
  23. console.log(`The sum of all predicted values is: ${sumOfNewValues}`);
  24. /**
  25. * Predict the next value in a histogram
  26. *
  27. * @param histogram The histogram to find the next value for
  28. * @returns The input histogram with its new value added
  29. */
  30. function PredictNextValue(histogram: Histogram): Histogram {
  31. const allDifferentials = [histogram];
  32. let differential = [];
  33. // Get all differentials until only an array of zeros remains
  34. do {
  35. differential = FindDifferential(allDifferentials[0]);
  36. allDifferentials.unshift(differential);
  37. } while (!ArrayIsOnlyDuplicates(differential));
  38. console.log(allDifferentials);
  39. while (allDifferentials.length > 1) {
  40. // Store the last value of previous differential, and remove that differential from the list
  41. const firstValueOfDifferential = allDifferentials.shift()?.shift() as number;
  42. // if (lastValueOfDifferential == undefined) {
  43. // throw new Error("There is no last value of previous differential!\n" + prevDifferential);
  44. // }
  45. // Predict the next value to be this last value + the last value of the previous differential
  46. const predictedValue = allDifferentials[0][0] - firstValueOfDifferential;
  47. if (Number.isNaN(predictedValue)) {
  48. throw new Error("Failed to find differentials for the following histograms!\n" + histogram);
  49. }
  50. // Push to this differential
  51. allDifferentials[0].unshift(predictedValue);
  52. }
  53. return allDifferentials[0];
  54. }