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) || []; const maps = mapStrings.map((mapString) => mapString .split("\n") .slice(1) .filter((x) => x.length) .map((s) => s.match(/\d+/g)?.map(Number) || []) .map(([destinationStart, sourceStart, rangeSize]) => ({ sourceStart, destinationStart, rangeSize, })), ); const locationNumbers = seeds.map((seed) => maps.reduce((currentNumber, mapRules) => { const validRule = mapRules.find( (rule) => currentNumber >= rule.sourceStart && currentNumber < rule.sourceStart + rule.rangeSize, ); if (!validRule) return currentNumber; return currentNumber - validRule.sourceStart + validRule.destinationStart; }, seed), ); const result = locationNumbers.reduce((acc, x) => Math.min(acc, x), Infinity); console.log({ result });