Advertisement
scibuff

Advent of Code 2023 - Day 20 - Part 2

Dec 20th, 2023
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.74 KB | Source Code | 0 0
  1. const solvePart2 = (input) => {
  2.   const data = parse(input);
  3.   const modules = data.modules;
  4.   const inputCycles = {};
  5.   for (const input of data.rxInputs) {
  6.     inputCycles[input] = {};
  7.     for (const module of Object.values(modules)) {
  8.       if (module.destinations.includes(input)) {
  9.         inputCycles[input][module.label] = 1; // fix the off-by-one
  10.       }
  11.     }
  12.   }
  13.   const numberOfCyclesToDetermine = Object.values(inputCycles).reduce((sum, e) => sum + Object.keys(e).length, 0);
  14.   let determinedCyclesCounter = 0;
  15.   for (let cycle = 0; determinedCyclesCounter < numberOfCyclesToDetermine; cycle++) {
  16.     const pulses = [
  17.       {
  18.         from: "button",
  19.         to: "broadcaster",
  20.         value: LOW_PULSE,
  21.       },
  22.     ];
  23.     while (pulses.length > 0) {
  24.       const pulse = pulses.shift(); // FIFO
  25.  
  26.       for (const input of data.rxInputs) {
  27.         if (pulse.to == input && inputCycles[input][pulse.from] && pulse.value == HIGH_PULSE) {
  28.           if (inputCycles[input][pulse.from] == 1) {
  29.             inputCycles[input][pulse.from] += cycle;
  30.             determinedCyclesCounter++;
  31.             if (determinedCyclesCounter == numberOfCyclesToDetermine) {
  32.               break;
  33.             }
  34.           }
  35.         }
  36.       }
  37.  
  38.       const module = modules[pulse.to];
  39.       if (!module) {
  40.         continue;
  41.       }
  42.       const newPulse = modulate(module, pulse);
  43.       if (!newPulse) {
  44.         continue;
  45.       }
  46.       for (const destination of module.destinations) {
  47.         pulses.push({
  48.           from: module.label,
  49.           to: destination,
  50.           value: newPulse,
  51.         });
  52.       }
  53.     }
  54.   }
  55.   return Math.min(...Object.values(inputCycles).map((e) => Object.values(e).reduce((product, e) => product * e, 1)));
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement