From 50848c9299ededef12261011eaca60037aabcb42 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Tue, 5 Dec 2023 23:35:39 +0300 Subject: feat(day-5): add part 2 solution --- day-5/script.ts | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) (limited to 'day-5/script.ts') diff --git a/day-5/script.ts b/day-5/script.ts index 2d18477..f0eb76e 100644 --- a/day-5/script.ts +++ b/day-5/script.ts @@ -3,8 +3,20 @@ import fs from "fs"; const input = fs.readFileSync("./input.txt").toString(); const [seedStr, ...mapStrings] = input.split("\n\n"); - -const seeds = seedStr.match(/\d+/g)?.map(Number) || []; +export function chunks(data: Array, chunkSize: number) { + return data.reduce((acc, value, index) => { + // Initialize a new chunk + if (index % chunkSize === 0) acc.push([]); + acc[acc.length - 1].push(value); + return acc; + }, [] as T[][]); +} + +const seedRanges = chunks(seedStr.match(/\d+/g)?.map(Number) || [], 2).map( + ([start, size]) => { + return { start, size }; + }, +); const maps = mapStrings.map((mapString) => mapString @@ -19,6 +31,19 @@ const maps = mapStrings.map((mapString) => })), ); +// We dont need to inspect whole seed ranges, instead we only select "interesting points" +// Interesting points lie at starts/end of ranges defined in our maps +const seeds = maps + .flatMap((ranges) => + ranges.flatMap((r) => [r.sourceStart, r.destinationStart + 1]), + ) + .filter((breakpoint) => + seedRanges.find( + (range) => + breakpoint >= range.start && breakpoint < range.start + range.size, + ), + ); + const locationNumbers = seeds.map((seed) => maps.reduce((currentNumber, mapRules) => { const validRule = mapRules.find( -- cgit v1.2.3