scibuff

Advent of Code 2023 - Day 19 - Part 2

Dec 19th, 2023
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.84 KB | Source Code | 0 0
  1. class Node {
  2.   /**
  3.    * line: "in{s<1351:px,qqz}"
  4.    * ranges: {
  5.    *  x: {min: 1, max: 4000},
  6.    *  m: {min: 1, max: 4000},
  7.    *  a: {min: 1, max: 4000},
  8.    *  s: {min: 1, max: 4000},
  9.    * }
  10.    */
  11.   constructor(workflows, label, ranges) {
  12.     this.ranges = ranges;
  13.     this.label = label;
  14.     this.children = [];
  15.     const rules = workflows[label];
  16.  
  17.     let remainingRanges = JSON.parse(JSON.stringify(ranges));
  18.     if (rules) {
  19.       for (const rule of rules) {
  20.         const newRanges = JSON.parse(JSON.stringify(remainingRanges));
  21.         remainingRanges = JSON.parse(JSON.stringify(newRanges));
  22.         if (rule.condition) {
  23.           if (rule.condition == "<") {
  24.             newRanges[rule.category].max = Math.max(newRanges[rule.category].min, rule.value - 1);
  25.             remainingRanges[rule.category].min = newRanges[rule.category].max + 1;
  26.           } else {
  27.             newRanges[rule.category].min = Math.min(newRanges[rule.category].max, rule.value + 1);
  28.             remainingRanges[rule.category].max = newRanges[rule.category].min - 1;
  29.           }
  30.         }
  31.         this.children.push(new Node(workflows, rule.next, newRanges));
  32.       }
  33.     }
  34.   }
  35.  
  36.   children() {
  37.     return this.children;
  38.   }
  39.   total() {
  40.     if (this.label == "R") {
  41.       return 0;
  42.     }
  43.     if (this.label == "A") {
  44.       return Object.keys(this.ranges).reduce((total, key) => {
  45.         return total * (this.ranges[key].max - this.ranges[key].min + 1);
  46.       }, 1);
  47.     }
  48.     return this.children.reduce((sum, child) => sum + child.total(), 0);
  49.   }
  50. }
  51. const solvePart2 = (input) => {
  52.   const data = parse(input);
  53.   const ranges = {
  54.     x: { min: 1, max: 4000 },
  55.     m: { min: 1, max: 4000 },
  56.     a: { min: 1, max: 4000 },
  57.     s: { min: 1, max: 4000 },
  58.   };
  59.   const root = new Node(data.workflows, "in", ranges);
  60.   return root.total();
  61. };
Advertisement
Add Comment
Please, Sign In to add comment