diff --git a/src/2019/day12.js b/src/2019/day12.js index 0b2d4c39..627d0364 100644 --- a/src/2019/day12.js +++ b/src/2019/day12.js @@ -1,3 +1,5 @@ +import { lcm } from '../utils/divisors.js'; + function parse(input) { return input .split('\n') @@ -28,21 +30,6 @@ function rotate(moons) { }); } -//lcm = a*b/gcd(a,b) -function lcm(numbers) { - return numbers - .map(x => Math.abs(x)) - .reduce((a, b) => { - const m = a * b; - while (b) { - const t = b; - b = a % b; - a = t; - } - return m / a; - }); -} - export function part1(input, rotations = 1000) { const moons = parse(input); for (let i = 0; i < rotations; i++) { diff --git a/src/2023/day08.js b/src/2023/day08.js index 5647da79..1216de81 100644 --- a/src/2023/day08.js +++ b/src/2023/day08.js @@ -1,41 +1,20 @@ +import { lcm } from '../utils/divisors.js'; + function parse(input) { let [steps, maps] = input.split('\n\n'); - maps = maps.split('\n').map(map => { - const [, node, left, right] = map.match(/^(.+) = \((.+), (.+)\)$/); - return { node, left, right }; - }); - maps = maps.reduce((acc, map) => ({ ...acc, [map.node]: map }), {}); + maps = maps.split('\n').reduce((acc, map) => { + const [, node, L, R] = map.match(/^(.+) = \((.+), (.+)\)$/); + return { ...acc, [node]: { L, R } }; + }, {}); return { steps, maps }; } function walk(current, steps, maps, dest = key => key === 'ZZZ') { let count = 0; - while (!dest(current)) { - for (let i = 0; i < steps.length; i++) { - count++; - const step = steps[i]; - if (step === 'L') { - current = maps[current].left; - } else if (step === 'R') { - current = maps[current].right; - } - } + for (count = 0; !dest(current); count++) { + for (let i = 0; i < steps.length; i++) current = maps[current][steps[i]]; } - return count; -} - -function lcm(numbers) { - return numbers - .map(x => Math.abs(x)) - .reduce((a, b) => { - const m = a * b; - while (b) { - const t = b; - b = a % b; - a = t; - } - return m / a; - }); + return count * steps.length; } export function part1(input) { @@ -45,9 +24,7 @@ export function part1(input) { export function part2(input) { const { steps, maps } = parse(input); - const current = Object.keys(maps).filter(key => key.endsWith('A')); - let counts = current.map(key => - walk(key, steps, maps, key => key.endsWith('Z')), - ); + const keys = Object.keys(maps).filter(key => key.endsWith('A')); + const counts = keys.map(x => walk(x, steps, maps, key => key.endsWith('Z'))); return lcm(counts); } diff --git a/src/utils/divisors.js b/src/utils/divisors.js index 6fed1463..c4dc6699 100644 --- a/src/utils/divisors.js +++ b/src/utils/divisors.js @@ -11,3 +11,18 @@ export function divisors(x) { } return result; } + +//lcm = a*b/gcd(a,b) +export function lcm(numbers) { + return numbers + .map(x => Math.abs(x)) + .reduce((a, b) => { + const m = a * b; + while (b) { + const t = b; + b = a % b; + a = t; + } + return m / a; + }); +}