From 63aae6749ded480eee0bf898c492c6ed1b0e1ca0 Mon Sep 17 00:00:00 2001 From: TobenderZephyr Date: Sat, 21 Dec 2024 11:50:36 +0100 Subject: [PATCH] day 08 part 2 updated with LCM. No more brute forcing --- 2023/day08/index.js | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/2023/day08/index.js b/2023/day08/index.js index f7ffcb6..be3a9d5 100644 --- a/2023/day08/index.js +++ b/2023/day08/index.js @@ -33,7 +33,7 @@ class DesertMap { } return this.#route.find(route => route.from === from)[towards] } - navigate_ghosts() { + navigate_brute() { this.setup() let i = 0 let start = this.#route.filter(route => route.from[2] === 'A') @@ -50,6 +50,34 @@ class DesertMap { console.log(this.steps + 1) } + lcm(numbers) { + function gcd(a, b) { + if (b === 0) { + return a; + } + return gcd(b, a % b); + } + return numbers.reduce((a, b) => a * b / gcd(a, b)); + } + + navigate_ghosts() { + this.setup() + let routes = this.#route.filter(route => route.from[2] === 'A') + .map(route => route.from) + let results = routes.map(route => { + let i = 0 + let steps = 0 + while (i < this.instructions.length | true) { + route = this.run(this.instructions[i], route) + ++steps + if (route[2] === 'Z') { return steps } + i = this.instructions.length - i === 1 ? 0 : i + 1 + } + }) + console.log(`LCM of ${results.join(", ")}`) + console.log(this.lcm(results)) + } + navigate() { this.setup() let i = 0