-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.js
112 lines (105 loc) · 3.02 KB
/
12.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const util = require('./util.js')
const TODAY = 12
const DIRECTIONS = ['EAST', 'SOUTH', 'WEST', 'NORTH']
function main() {
const ops = util.getInputFromFile(TODAY)
.split('\n')
console.log("Part 1: " + part1(ops))
console.log("Part 2: " + part2(ops))
}
function part1(ops) {
let pos = [0, 0]
let direction = 0
ops.forEach(op => {
let a = op.slice(0, 1)
let b = parseInt(op.slice(1))
switch (a) {
case 'E':
pos[1] += b
break
case 'S':
pos[0] += b
break
case 'W':
pos[1] += -b
break
case 'N':
pos[0] += -b
break
case 'R':
direction = (direction + b/90) % 4
break
case 'L':
direction = ((direction - b/90) + 4) % 4
break
case 'F':
switch (DIRECTIONS[direction]) {
case 'EAST':
pos[1] += b
break
case 'SOUTH':
pos[0] += b
break
case 'WEST':
pos[1] += -b
break
case 'NORTH':
pos[0] += -b
break
}
}
})
return Math.abs(pos[0]) + Math.abs(pos[1])
}
function part2(ops) {
let pos = [0, 0]
let waypoint = [-1, 10]
ops.forEach(op => {
let a = op.slice(0, 1)
let b = parseInt(op.slice(1))
switch (a) {
case 'E':
waypoint[1] += b
break
case 'S':
waypoint[0] += b
break
case 'W':
waypoint[1] += -b
break
case 'N':
waypoint[0] += -b
break
case 'R':
switch (b) {
case 90:
waypoint = [waypoint[1], -waypoint[0]]
break
case 180:
waypoint = [-waypoint[0], -waypoint[1]]
break
case 270:
waypoint = [-waypoint[1], waypoint[0]]
break
}
break
case 'L':
switch (b) {
case 90:
waypoint = [-waypoint[1], waypoint[0]]
break
case 180:
waypoint = [-waypoint[0], -waypoint[1]]
break
case 270:
waypoint = [waypoint[1], -waypoint[0]]
break
}
break
case 'F':
pos = [pos[0] + (waypoint[0] * b), pos[1] + (waypoint[1] * b)]
}
})
return Math.abs(pos[0]) + Math.abs(pos[1])
}
main();