Advent of Code 2023-25 simplified v2

 avatar
radulle
javascript
2 months ago
1.3 kB
131
Indexable
Never
const { exec } = require("child_process");
const { input, consoleTime } = require("lib");
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);
    }
  }

  const total = Object.keys(graph).length;
  let count = 0;
  function explore(node, visited = new Set()) {
    if (visited.has(node)) return;
    visited.add(node), count++;
    for (const key of node) explore(graph[key], visited);
  }
  explore(Object.values(graph)[0]);

  return count * (total - count);
}
Leave a Comment