-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDive.js
77 lines (72 loc) · 1.79 KB
/
Dive.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
const fs = require("fs");
const content = fs.readFileSync(
"dive-input.txt",
{ encoding: "utf-8" },
(err) => {
if (err) {
console.log(err);
}
}
);
const commands = content
.split("\n") // split input on new line
.filter((x) => Boolean(x)) // return array with only lines containing value i.e no empty lines, only truthy lines - same as .filter(Boolean)
.map((line) => {
// map each line to a direction and a speed, push into new array
let arr = [];
let [direction, speed] = line.split(" ");
arr.push(direction, parseInt(speed));
return arr;
});
// part 1
const steerSubmarine = (commands) => {
let horizontal = 0;
let depth = 0;
// for each command in array of commands, use switch to see which direction we are going
// adjust for that direction
for (const command of commands) {
switch (command[0]) {
case "forward":
horizontal += command[1];
break;
case "up":
depth -= command[1];
break;
case "down":
depth += command[1];
break;
default:
break;
}
}
// result is depth * horizontal
return depth * horizontal;
};
// part two
const steerSubmarineWithAim = (commands) => {
let horizontal = 0;
let depth = 0;
let aim = 0;
for (const command of commands) {
switch (command[0]) {
case "forward":
horizontal += command[1];
depth += aim * command[1];
break;
case "up":
aim -= command[1];
break;
case "down":
aim += command[1];
break;
default:
break;
}
}
// result is depth * horizontal
return depth * horizontal;
};
const resultPartOne = steerSubmarine(commands);
const resultPartTwo = steerSubmarineWithAim(commands);
console.log(resultPartOne);
console.log(resultPartTwo);