import fs from "fs"; const [directions, _, ...lines] = fs .readFileSync("./input.txt") .toString() .split("\n") .slice(0, -1); const nodes = lines .map((line) => { const match = line.match(/(...) = \((...), (...)\)/); if (!match) throw new Error("Could not match"); return { node: match[1], left: match[2], right: match[3], }; }) .map((node, index, nodes) => ({ node: index, left: nodes.findIndex((n) => n.node === node.left), right: nodes.findIndex((n) => n.node === node.right), })); const targetNumber = lines.findIndex((line) => line.startsWith("ZZZ")); let currentNumber = lines.findIndex((line) => line.startsWith("AAA")); let steps = 0; while (currentNumber !== targetNumber) { const direction = ( { L: "left", R: "right", } as const )[directions[steps % directions.length]]; if (!direction) throw new Error("Invalid direction"); currentNumber = nodes[currentNumber][direction]; steps++; } console.log({ steps });