diff options
Diffstat (limited to 'day-5/script.ts')
-rw-r--r-- | day-5/script.ts | 29 |
1 files changed, 27 insertions, 2 deletions
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<T>(data: Array<T>, 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( |