-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.js
56 lines (48 loc) · 1.07 KB
/
day2.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
const fs = require('fs');
const moves = fs.readFileSync('./data/day2.txt', 'utf8').split('\n');
const values = moves.reduce(
(acc, move) => {
const [direction, value] = move.split(' ');
switch (direction) {
case 'forward':
acc.horizontalDistance += parseInt(value);
break;
case 'up':
acc.totalDepth -= parseInt(value);
break;
case 'down':
acc.totalDepth += parseInt(value);
break;
}
return acc;
},
{ horizontalDistance: 0, totalDepth: 0 }
);
console.log(values.horizontalDistance * values.totalDepth);
// part 2
let aim = 0;
let depth = 0;
let distance = 0;
const sampleMoves = [
'forward 5',
'down 5',
'forward 8',
'up 3',
'down 8',
'forward 2',
];
moves.map((move) => {
const direction = move.split(' ')[0];
const units = parseInt(move.split(' ')[1]);
if (direction === 'forward') {
distance += units;
depth = depth + units * aim;
}
if (direction === 'up') {
aim -= units;
}
if (direction === 'down') {
aim += units;
}
});
console.log(depth * distance);