const fs = require("fs"); let [rules, messages] = fs .readFileSync("input", "utf-8") .trim() .split("\n\n") .map((part) => part.split("\n")); rules = rules .map((line) => line.split(": ")) .map(([num, rule]) => [parseInt(num), rule]) .sort((a, b) => a[0] - b[0]) .map(([_, rule]) => rule); console.log(rules); console.log("="); // console.log(messages); function getRegex(idx) { const rule = rules[idx]; if (rule.startsWith('"')) { return rule.slice(1, rule.length - 1); } let regex = ""; let multiple = false; for (const symbol of rule.split(" ")) { if (symbol === "|") { regex = "(" + regex + "|"; multiple = true; } else { regex = regex + getRegex(parseInt(symbol)); } } regex = multiple ? regex + ")" : regex; rules[idx] = '"' + regex + '"'; return regex; } const regex = new RegExp(`^${getRegex(0)}$`); console.log(rules); console.log(regex); let sum = 0; for (const message of messages) { if (regex.test(message)) sum++; } console.log(sum);