scibuff

Advent of Code 2023 - Day 19 - Parsing

Dec 19th, 2023
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.21 KB | Source Code | 0 0
  1. const parseWorkflowRules = (s) => {
  2.   const parts = s.split(",");
  3.   const rules = [];
  4.   for (const el of parts) {
  5.     const m = el.match(/(a|m|s|x)(<|>)(\d+):(\w+)/);
  6.     if (m) {
  7.       rules.push({
  8.         category: m[1],
  9.         condition: m[2],
  10.         value: parseInt(m[3]),
  11.         next: m[4],
  12.       });
  13.     } else {
  14.       rules.push({
  15.         condition: null,
  16.         next: el,
  17.       });
  18.     }
  19.   }
  20.   return rules;
  21. };
  22. const parseWorkflow = (line) => {
  23.   const matches = line.match(/(\w+){(.*)}/);
  24.   return {
  25.     label: matches[1],
  26.     rules: parseWorkflowRules(matches[2]),
  27.   };
  28. };
  29. const parsePart = (line) => {
  30.   return line.split(",").reduce((part, e) => {
  31.     const m = e.match(/(x|m|a|s)=(\d+)/);
  32.     part[m[1]] = parseInt(m[2]);
  33.     return part;
  34.   }, {});
  35. };
  36. const parse = (input) => {
  37.   const sections = input.trim().split(/\r?\n\r?\n/);
  38.   const lines1 = utils.getInputLines(sections[0]);
  39.   const lines2 = utils.getInputLines(sections[1]);
  40.   const workflows = {};
  41.   for (const line of lines1) {
  42.     const flow = parseWorkflow(line);
  43.     workflows[flow.label] = flow.rules;
  44.   }
  45.   const parts = lines2.map(parsePart);
  46.   return {
  47.     parts: parts,
  48.     workflows: workflows,
  49.   };
  50. };
  51.  
Advertisement
Add Comment
Please, Sign In to add comment