Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const modulate = (module, pulse) => {
- switch (module.type) {
- case "b": {
- return pulse.value;
- }
- case "%": {
- if (pulse.value == HIGH_PULSE) {
- return null;
- }
- module.on = !module.on;
- return module.on ? HIGH_PULSE : LOW_PULSE;
- }
- case "&": {
- module.inputs[pulse.from] = pulse.value;
- for (const p of Object.values(module.inputs)) {
- if (p == LOW_PULSE) {
- return HIGH_PULSE;
- }
- }
- return LOW_PULSE;
- }
- }
- if (module.label == "broadcaster") {
- return pulse;
- }
- };
- const solvePart1 = (input) => {
- const modules = parse(input).modules;
- const cycles = 1_000;
- const counters = {
- low: 0,
- high: 0,
- };
- for (let i = 0; i < cycles; i++) {
- const pulses = [
- {
- from: "button",
- to: "broadcaster",
- value: LOW_PULSE,
- },
- ];
- while (pulses.length > 0) {
- const pulse = pulses.shift(); // FIFO
- counters[pulse.value]++;
- const module = modules[pulse.to];
- if (!module) {
- continue;
- }
- const newPulse = modulate(module, pulse);
- if (!newPulse) {
- continue;
- }
- for (const destination of module.destinations) {
- pulses.push({
- from: module.label,
- to: destination,
- value: newPulse,
- });
- }
- }
- }
- return counters.low * counters.high;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement