-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05.js
78 lines (63 loc) · 1.77 KB
/
05.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
66
67
68
69
70
71
72
73
74
75
76
77
78
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {matchNumbers, readInput} from '../../../util.js';
const directoryPath = path.dirname(fileURLToPath(import.meta.url));
const input = await readInput(directoryPath);
const seedMap = input.trim().split('\n\n');
const initialSeeds = matchNumbers(seedMap[0]);
function convertInputToMap(seedMapInput) {
return seedMapInput
.split(':\n')[1]
.split('\n')
.map(line => {
const numbers = matchNumbers(line);
return {
destinationRangeStart: numbers[0],
sourceRangeStart: numbers[1],
rangeLength: numbers[2],
};
});
}
const seedMaps = seedMap
.slice(1, seedMap.length)
.map(currentSeedMap => convertInputToMap(currentSeedMap));
function findSeedLocationNumber(seed) {
let currentPosition = seed;
for (const currentSeedMap of seedMaps) {
let destination;
for (const mapLine of currentSeedMap) {
if (
mapLine.sourceRangeStart <= currentPosition &&
currentPosition <= mapLine.sourceRangeStart + mapLine.rangeLength
) {
destination =
mapLine.destinationRangeStart +
(currentPosition - mapLine.sourceRangeStart);
break;
}
}
if (destination) {
currentPosition = destination;
}
}
return currentPosition;
}
function findLowestSeedLocationNumber(seeds) {
let lowestLocationNumber;
for (const seed of seeds) {
const currentPosition = findSeedLocationNumber(seed);
if (!lowestLocationNumber) {
lowestLocationNumber = currentPosition;
}
if (currentPosition < lowestLocationNumber) {
lowestLocationNumber = currentPosition;
}
}
return lowestLocationNumber;
}
const lowestInitialSeedsLocationNumber =
findLowestSeedLocationNumber(initialSeeds);
console.log(
'Lowest location number for initial seeds:',
lowestInitialSeedsLocationNumber,
);