-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_12.2.js
More file actions
83 lines (74 loc) · 1.79 KB
/
day_12.2.js
File metadata and controls
83 lines (74 loc) · 1.79 KB
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
// Puzzle 12.1:
// Move ship (x,y) according to instructions (cmd, val), where cmd:
// North,East,South,West: change ship direction vector;
// Left, Right: rotate ship direction vector by amount of degrees;
// Forward: move ship by amount of steps on direction vector.
//
// The initial direction vector is [10, 1]
// Find the Manhattan distance the ship moved.
'use strict'
const rawInput = []
// The actual input
rawInput[0] = require('./data/day_12')
// The 1-st example
rawInput[1] = `F10
N3
F7
R90
F11`
const assert = require('assert-fine')
const tr = s => {
return [s[0], s.substring(1) * 1]
}
let input = rawInput[0].split('\n').map(tr)
const q2 = () => {
let x = 0, y = 0, direction = [10, 1]
for (let i = 0; input[i] !== undefined; ++i) {
let [cmd, v] = input[i]
switch (cmd) {
case 'F':
x += v * direction[0]
y += v * direction[1]
break
case 'L':
v = 360 - v
// Fall through
case 'R':
switch (v) {
case 0:
break
case 90:
direction = [direction[1], -direction[0]]
break
case 180:
direction = [-direction[0], -direction[1]]
break
case 270:
direction = [-direction[1], direction[0]]
break
default:
assert(0, 'bad angle [%i]', i, input[i])
}
break
case 'N':
direction[1] += v
break
case 'E':
direction[0] += v
break
case 'S':
direction[1] -= v
break
case 'W':
direction[0] -= v
break
default:
assert(0, 'bad command [%i]', i, input[i])
}
}
return { x, y, d: Math.abs(x) + Math.abs(y) }
}
assert.hook(() => {
console.log('breakpoint')
})
console.log('Q1', q2())