-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday07.js
52 lines (43 loc) · 1.26 KB
/
day07.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
const fs = require("fs");
const crabs = fs
.readFileSync("day07.txt", { encoding: "utf-8" }) // read day??.txt content
.replace(/[\r\n]/g, "") // remove all \r characters to avoid issues on Windows
.split(",") // Split on newline
.map(Number); // Parse each line into a number
crabs.sort((a, b) => a - b);
function median(array) {
const internalArray = [...array];
internalArray.sort((a, b) => a - b);
if (internalArray.length % 2 === 0) {
return (
(internalArray[internalArray.length / 2 - 1] +
internalArray[internalArray.length / 2]) /
2
);
} else {
return internalArray[Math.floor(internalArray.length / 2)];
}
}
function part1() {
const meetAt = median(crabs);
const fuelCost = crabs
.map((position) => Math.abs(position - meetAt))
.reduce((a, b) => a + b, 0);
console.log(fuelCost);
}
part1();
function part2() {
const highestPosition = crabs[crabs.length - 1];
const allCosts = Array(highestPosition).fill(0);
for (let i = 0; i < highestPosition; i++) {
const fuelCost = crabs
.map(
(position) =>
(Math.abs(position - i) * (1 + Math.abs(position - i))) / 2
)
.reduce((a, b) => a + b, 0);
allCosts[i] = fuelCost;
}
console.log(Math.min(...allCosts));
}
part2();