import {Range, Seq} from "immutable"; import {chunk} from "lodash"; import fs from "fs"; type MapRange = { source: number; destination: number; size: number; } const parseSeeds = (input: string): Seq.Indexed => { const [_, seedString] = input.split('seeds: '); return chunk(seedString.split(' '), 2).reduce((seeds, [start, size]) => { return seeds.concat(Range(Number(start), Number(start) + Number(size))); }, Seq.Indexed()); } const mapMapper = (input: string): MapRange[] => { const [_, ...lines] = input.split('\n'); return lines.map(line => { const [dest, source, size] = line.split(' ').map(Number); return { source: source, destination: dest, size } }); } const seedMapper = (seed: number, map: MapRange[]): number => { const mapped = map.find(({source, destination, size}) => { return seed >= source && seed < source + size; }); if (!mapped) { return seed; } return seed - mapped.source + mapped.destination; } export const mapSeedToLocation = (input: string): number => { const [seedsStr, ...mapStrings] = input.split('\n\n'); const seeds = parseSeeds(seedsStr); const maps = mapStrings.map(mapMapper); const mapped = seeds.map(seed => { return maps.reduce((seed, map) => seedMapper(seed, map), seed); }); return mapped.min()!; } export const runDayFive = () => { const input = fs.readFileSync('./inputs/day_five_input.txt', 'utf8').trimEnd(); const result = mapSeedToLocation(input); console.log(`Day Five: ${result}`); }