Advertisement
scibuff

Advent of Code 2023 - Day 20 - Part 1

Dec 20th, 2023
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.43 KB | Source Code | 0 0
  1. const modulate = (module, pulse) => {
  2.   switch (module.type) {
  3.     case "b": {
  4.       return pulse.value;
  5.     }
  6.     case "%": {
  7.       if (pulse.value == HIGH_PULSE) {
  8.         return null;
  9.       }
  10.       module.on = !module.on;
  11.       return module.on ? HIGH_PULSE : LOW_PULSE;
  12.     }
  13.     case "&": {
  14.       module.inputs[pulse.from] = pulse.value;
  15.       for (const p of Object.values(module.inputs)) {
  16.         if (p == LOW_PULSE) {
  17.           return HIGH_PULSE;
  18.         }
  19.       }
  20.       return LOW_PULSE;
  21.     }
  22.   }
  23.   if (module.label == "broadcaster") {
  24.     return pulse;
  25.   }
  26. };
  27.  
  28. const solvePart1 = (input) => {
  29.   const modules = parse(input).modules;
  30.   const cycles = 1_000;
  31.   const counters = {
  32.     low: 0,
  33.     high: 0,
  34.   };
  35.   for (let i = 0; i < cycles; i++) {
  36.     const pulses = [
  37.       {
  38.         from: "button",
  39.         to: "broadcaster",
  40.         value: LOW_PULSE,
  41.       },
  42.     ];
  43.     while (pulses.length > 0) {
  44.       const pulse = pulses.shift(); // FIFO
  45.       counters[pulse.value]++;
  46.       const module = modules[pulse.to];
  47.       if (!module) {
  48.         continue;
  49.       }
  50.       const newPulse = modulate(module, pulse);
  51.       if (!newPulse) {
  52.         continue;
  53.       }
  54.       for (const destination of module.destinations) {
  55.         pulses.push({
  56.           from: module.label,
  57.           to: destination,
  58.           value: newPulse,
  59.         });
  60.       }
  61.     }
  62.   }
  63.   return counters.low * counters.high;
  64. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement