1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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 });
|