This repository has been archived by the owner on Oct 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rain-risk.js
97 lines (88 loc) · 2.53 KB
/
rain-risk.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const fs = require("fs");
let values = fs.readFileSync("input.txt", "utf8").split("\r\n");
const delta = {
N: [0, 1],
E: [1, 0],
S: [0, -1],
W: [-1, 0],
}
function turn(direction, degrees, facing) {
let directions = Object.keys(delta)
let current = directions.indexOf(facing)
if (direction == 'R') {
return directions[
(current+(degrees/90)) % directions.length]
} else if (direction == 'L') {
return directions[
(current-(degrees/90) + directions.length) % directions.length]
}
}
function move(pos, amount, direction) {
return [
pos[0] + amount * delta[direction][0],
pos[1] + amount * delta[direction][1]
]
}
function solve_part_one() {
let directions = Object.keys(delta)
let facing = 'E'
let pos = [0, 0]
for (let value of values) {
let action = value[0]
let amount = parseInt(value.substring(1))
if (directions.includes(action)) {
pos = move(pos, amount, action)
} else if (action == 'F') {
pos = move(pos, amount, facing)
} else {
facing = turn(action, amount, facing)
}
}
return Math.abs(pos[0]) + Math.abs(pos[1])
}
function move_towards_waypoint(pos, waypoint, amount) {
return [
pos[0] + (amount * waypoint[0]),
pos[1] + (amount * waypoint[1])
]
}
function rotate_waypoint(pos, waypoint, action, amount) {
if (amount == 180) {
return [
-waypoint[0],
-waypoint[1]
]
} else if ((action == 'L' && amount == 90) || (action == 'R' && amount == 270)) {
return [
-waypoint[1],
waypoint[0]
]
} else if ((action == 'R' && amount == 90) || (action == 'L' && amount == 270)) {
return [
waypoint[1],
-waypoint[0]
]
} else {
console.log('Invalid Rotation:', action+amount)
return waypoint
}
}
function solve_part_two() {
let directions = Object.keys(delta)
let pos = [0, 0]
let waypoint = [10, 1]
for (let value of values) {
let action = value[0]
let amount = parseInt(value.substring(1))
if (directions.includes(action)) {
waypoint = move(waypoint, amount, action)
} else if (action == 'F') {
pos = move_towards_waypoint(pos, waypoint, amount)
} else {
waypoint = rotate_waypoint(pos, waypoint, action, amount)
}
}
return Math.abs(pos[0]) + Math.abs(pos[1])
}
console.log(solve_part_one())
console.log(solve_part_two())