-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday07.ts
105 lines (90 loc) · 2.57 KB
/
day07.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// import lodash and fs
import * as _ from "lodash";
import * as fs from "fs";
// function to read input of comma separated numbers
function readInput(fileName: string): number[] {
// read the file
const input = fs.readFileSync(fileName, "utf8");
// split the input by comma
const inputArray = input.split(",");
// return the input as an array of numbers
return inputArray.map(Number);
}
function part1() {
// read day07sample
const input = readInput("day07input");
// input are horizontal crab positions.
// increase a crab position by 1 costs 1 fuel
// decrease a crab position by 1 costs 1 fuel
// calculate cost for moving all crabs to position 2
const cost = input.reduce((acc, curr) => acc + Math.abs(curr - 2), 0);
// find min and max positions of input
const min = _.min(input) ?? 0;
const max = _.max(input) ?? 0;
// find target position between min and max with lowest cost
const target = _.range(min, max + 1).reduce(
(acc: any, current) => {
const cost = input.reduce(
(acc, curr) => acc + Math.abs(curr - current),
0
);
if (cost < acc.cost) {
return {
cost: cost,
position: current,
};
}
return acc;
},
{
cost: Number.MAX_VALUE,
position: 0,
}
);
// print target
console.log(target);
// output cost
// console.log(`Part 1: ${cost}`);
}
// function calcCost, input number start, input number target
// dist is the distance from start to target
// cost is dist * (dist + 1) / 2
function calcCost(start: number, target: number): number {
const dist = Math.abs(start - target);
return (dist * (dist + 1)) / 2;
}
function part2() {
// read day07input
const input = readInput("day07input");
// input are horizontal crab positions.
// calculate cost for moving all crab to position 5 using calcCost
const cost = input.reduce((acc, curr) => acc + calcCost(curr, 5), 0);
// find min and max positions of input
const min = _.min(input) ?? 0;
const max = _.max(input) ?? 0;
// find target position between min and max with lowest cost
const target = _.range(min, max + 1).reduce(
(acc: any, current) => {
const cost = input.reduce(
(acc, curr) => acc + calcCost(curr, current),
0
);
if (cost < acc.cost) {
return {
cost: cost,
position: current,
};
}
return acc;
},
{
cost: Number.MAX_VALUE,
position: 0,
}
);
// print target
console.log(target);
// print cost
// console.log(`Part 2: ${cost}`);
}
part2();