Advent of Code 2023-25
const { exec } = require("child_process"); const { writeFile } = require("fs").promises; function solve(input) { return calc(parse(input)); } function parse(input) { return input .split("\n") .map((l) => l.split(": ").map((m) => m.split(" ").filter(Boolean))); } function calc(data) { const graphViz = false; // Set to true to generate a GraphViz file if (graphViz) { let dot = "digraph G {\n"; for (const [from, to] of data) { dot += ` ${from}`; if (to.length) dot += ` -> ${to.join(",")}`; dot += "\n"; } dot += "}"; writeFile("data.dot", dot).then(() => exec("dot -Tsvg data.dot -o data.svg") ); } // Remove three edges from the graph manually // vqj -> szh // jbx -> sml // zhb -> vxr const graph = {}; for (const [from, to] of data) { if (!graph[from]) graph[from] = []; for (const t of to) { if (!graph[t]) graph[t] = []; graph[from].push(t); graph[t].push(from); } } let count, count0; function explore(node, visited = new Set()) { if (visited.has(node)) return; visited.add(node), count++; for (const key of node) explore(graph[key], visited); } (count = 0), explore(graph["bkd"]), (count0 = count); (count = 0), explore(graph["qlt"]); return count0 * count; }
Leave a Comment