diff options
author | eug-vs <eugene@eug-vs.xyz> | 2023-12-09 02:23:56 +0300 |
---|---|---|
committer | eug-vs <eugene@eug-vs.xyz> | 2023-12-09 02:23:56 +0300 |
commit | e57d0b97c8cb365d7d0a3ee7a0fc9294d2c8dcee (patch) | |
tree | 9ee0e7f53abb17f33e1a22c4fa179e67d66afb59 | |
parent | 592fb33a20ed5438f0bee9de04f2f01e8369588b (diff) | |
download | aoc-2023-e57d0b97c8cb365d7d0a3ee7a0fc9294d2c8dcee.tar.gz |
feat(day-8): add part 2 solution
-rw-r--r-- | day-8/script.ts | 49 |
1 files changed, 32 insertions, 17 deletions
diff --git a/day-8/script.ts b/day-8/script.ts index 71849c7..87e33cd 100644 --- a/day-8/script.ts +++ b/day-8/script.ts @@ -1,5 +1,13 @@ import fs from "fs"; +function gcd(a: number, b: number) { + return !b ? a : gcd(b, a % b); +} + +function lcm(a: number, b: number) { + return (a * b) / gcd(a, b); +} + const [directions, _, ...lines] = fs .readFileSync("./input.txt") .toString() @@ -17,26 +25,33 @@ const nodes = lines }; }) .map((node, index, nodes) => ({ + name: node.node, 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++; -} +const [startingNodes, terminalNodes] = ["A", "Z"].map((char) => + nodes.filter((n) => n.name.endsWith(char)).map((n) => n.node), +); + +const result = startingNodes + .map((node) => { + let steps = 0; + while (!terminalNodes.includes(node)) { + const direction = ( + { + L: "left", + R: "right", + } as const + )[directions[steps % directions.length]]; + if (!direction) throw new Error("Invalid direction"); + + node = nodes[node][direction]; + steps++; + } + return steps; + }) + .reduce((acc, x) => lcm(acc, x), 1); -console.log({ steps }); +console.log({ result }); |