-
Notifications
You must be signed in to change notification settings - Fork 15
/
part-two.js
83 lines (73 loc) · 1.78 KB
/
part-two.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
const manhattan = require('manhattan');
const input = require('./input');
let directions = ['N', 'E', 'S', 'W'];
// North
let current_direction = 0;
const rotate = l_or_r => {
if (l_or_r === 'R') {
current_direction = (current_direction + 1) % directions.length;
} else {
// Turning left is like turning right 3 times.
// Makes it easier than I always increase and don't have to worry about the negative case
current_direction = (current_direction + 3) % directions.length;
}
};
const hasVisited = c => {
let point = c.join(',');
if (visited[point]) {
return true;
} else {
visited[point] = true;
return false;
}
};
let coords = [0, 0];
let visited = { '0,0': true };
let move = {
N: v => {
for (let i = 0; i < v; i++) {
coords[1]--;
if (hasVisited(coords)) {
return true;
}
}
return false;
},
E: v => {
for (let i = 0; i < v; i++) {
coords[0]++;
if (hasVisited(coords)) {
return true;
}
}
return false;
},
S: v => {
for (let i = 0; i < v; i++) {
coords[1]++;
if (hasVisited(coords)) {
return true;
}
}
return false;
},
W: v => {
for (let i = 0; i < v; i++) {
coords[0]--;
if (hasVisited(coords)) {
return true;
}
}
return false;
},
};
for (let i = 0; i < input.length; i++) {
let action = input[i];
let { turn, walk } = action;
rotate(turn);
let facing = directions[current_direction];
if (move[facing](walk)) {
break;
}
}
console.log(manhattan([0, 0], coords));