From c59491b88d3aec91208426d15513d28f8862b930 Mon Sep 17 00:00:00 2001 From: Carlos de la Orden Date: Thu, 28 Dec 2023 02:16:26 +0100 Subject: [PATCH] day 8 part 2: lcm --- src/days/8/index.ts | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/days/8/index.ts b/src/days/8/index.ts index 51c4988..d023f82 100644 --- a/src/days/8/index.ts +++ b/src/days/8/index.ts @@ -1,6 +1,6 @@ import { explode, splitLines } from '@/lib/utils' import assert from 'assert' -import { pipe } from 'remeda' +import { map, pipe, reduce } from 'remeda' type CamelMap = { movements: number[] @@ -27,10 +27,14 @@ const parseInput = (s: string): CamelMap => } }) -const countSteps = (m: CamelMap): number => { +const countSteps = ( + m: CamelMap, + isEnding: (n: string) => boolean = (n) => n === 'ZZZ', + startAt = 'AAA' +): number => { let count = 0 - let currentNode = 'AAA' - while (currentNode !== 'ZZZ') { + let currentNode = startAt + while (!isEnding(currentNode)) { const nextMov = m.movements[count % m.movements.length] as number currentNode = m.nodes.get(currentNode)?.at(nextMov) as string count++ @@ -38,6 +42,21 @@ const countSteps = (m: CamelMap): number => { return count } +const gcd = (x: number, y: number): number => { + if (y === 0) return x + return gcd(y, x % y) +} +const lcm = (x: number, y: number) => (x * y) / gcd(x, y) + +const calculateStartingPaths = (m: CamelMap) => { + return pipe( + m, + (m) => Array.from(m.nodes.keys()).filter((n) => n.endsWith('A')), + map((s) => countSteps(m, (n) => n.endsWith('Z'), s)), + reduce(lcm, 1) + ) +} + export async function day8PartOne(sample: string, input: string) { assert(sample && input, 'Bad input data') const solution = pipe(input, parseInput, countSteps) @@ -46,4 +65,6 @@ export async function day8PartOne(sample: string, input: string) { export async function day8PartTwo(sample: string, input: string) { assert(sample && input, 'Bad input data') + const solution = pipe(input, parseInput, calculateStartingPaths) + console.log('Part two: %d', solution) }