-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathday02.js
60 lines (56 loc) · 1.52 KB
/
day02.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
'use strict';
const fs = require('fs');
fs.readFile('day02.txt', 'utf-8', (err, input) => {
if (err) throw err;
let lines = input.trim().split('\n');
let data = lines.map(parseLine);
dive1(data);
dive2(data);
});
function parseLine(line) {
let parts = line.split(' ');
return { direction: parts[0], distance: Number(parts[1]) };
}
function dive1(data) {
let depth = 0, range = 0;
data.forEach(instr => {
let dist = instr.distance;
switch (instr.direction) {
case 'forward':
range += dist;
break;
case 'up':
depth -= dist;
depth = Math.max(0, depth);
break;
case 'down':
depth += dist;
break;
default:
throw `Unexpected direction: ${instr.direction}`;
}
});
console.log(depth * range);
}
function dive2(data) {
let aim = 0, depth = 0, range = 0;
data.forEach(instr => {
let dist = instr.distance;
switch (instr.direction) {
case 'forward':
range += dist;
depth += (dist * aim)
depth = Math.max(0, depth);
break;
case 'up':
aim -= dist;
break;
case 'down':
aim += dist;
break;
default:
throw new Error(`Unexpected direction: ${instr.direction}`);
}
});
console.log(depth * range);
}