Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- /**
- * line: "in{s<1351:px,qqz}"
- * ranges: {
- * x: {min: 1, max: 4000},
- * m: {min: 1, max: 4000},
- * a: {min: 1, max: 4000},
- * s: {min: 1, max: 4000},
- * }
- */
- constructor(workflows, label, ranges) {
- this.ranges = ranges;
- this.label = label;
- this.children = [];
- const rules = workflows[label];
- let remainingRanges = JSON.parse(JSON.stringify(ranges));
- if (rules) {
- for (const rule of rules) {
- const newRanges = JSON.parse(JSON.stringify(remainingRanges));
- remainingRanges = JSON.parse(JSON.stringify(newRanges));
- if (rule.condition) {
- if (rule.condition == "<") {
- newRanges[rule.category].max = Math.max(newRanges[rule.category].min, rule.value - 1);
- remainingRanges[rule.category].min = newRanges[rule.category].max + 1;
- } else {
- newRanges[rule.category].min = Math.min(newRanges[rule.category].max, rule.value + 1);
- remainingRanges[rule.category].max = newRanges[rule.category].min - 1;
- }
- }
- this.children.push(new Node(workflows, rule.next, newRanges));
- }
- }
- }
- children() {
- return this.children;
- }
- total() {
- if (this.label == "R") {
- return 0;
- }
- if (this.label == "A") {
- return Object.keys(this.ranges).reduce((total, key) => {
- return total * (this.ranges[key].max - this.ranges[key].min + 1);
- }, 1);
- }
- return this.children.reduce((sum, child) => sum + child.total(), 0);
- }
- }
- const solvePart2 = (input) => {
- const data = parse(input);
- const ranges = {
- x: { min: 1, max: 4000 },
- m: { min: 1, max: 4000 },
- a: { min: 1, max: 4000 },
- s: { min: 1, max: 4000 },
- };
- const root = new Node(data.workflows, "in", ranges);
- return root.total();
- };
Advertisement
Add Comment
Please, Sign In to add comment