-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
65 lines (60 loc) · 1.81 KB
/
solution.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const fs = require('fs');
function processSeeds(input, part) {
let [seeds, ...maps] = input.split('\n\n');
seeds = seeds.match(/\d+/g).map(Number);
if (part === 'part1') {
for (let map of maps) {
map = map
.split('\n')
.slice(1)
.map((line) => line.match(/\d+/g).map(Number));
for (let i = 0; i < seeds.length; i++) {
const seed = seeds[i];
for (const [dest, source, len] of map) {
if (seed >= source && seed < source + len) {
seeds[i] = seeds[i] - source + dest;
break;
}
}
}
}
return Math.min(...seeds);
} else {
const nextSeeds = [];
for (let i = 0; i < seeds.length; i += 2) {
nextSeeds.push([seeds[i], seeds[i] + seeds[i + 1] - 1]);
}
seeds = nextSeeds;
for (let map of maps) {
map = map
.split('\n')
.slice(1)
.map((line) => line.match(/\d+/g).map(Number));
const movedSeeds = [];
for (const [dest, source, len] of map) {
const unmovedSeeds = [];
for (const [start, end] of seeds) {
if (start < source + len && end >= source) {
movedSeeds.push([
Math.max(start, source) - source + dest,
Math.min(end, source + len - 1) - source + dest,
]);
}
if (start < source) {
unmovedSeeds.push([start, Math.min(end, source - 1)]);
}
if (end >= source + len) {
unmovedSeeds.push([Math.max(start, source + len), end]);
}
}
seeds = unmovedSeeds;
}
seeds.push(...movedSeeds);
}
return Math.min(...seeds.flat());
}
}
const input = fs.readFileSync('input.txt', 'utf8').trimEnd();
for(part of ['part1', 'part2']) {
console.log(part, ': ', processSeeds(input, part));
}