forked from vanessayuenn/advent-of-code-2016
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.js
83 lines (73 loc) · 1.75 KB
/
day1.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 input = require('./day1-input.js').split(', ');
const getNextDir = (turn) =>
(4 + (turn === 'R' ? currDirId + 1 : currDirId - 1)) % 4;
const getNextPos = (x, y, dir, steps) => {
switch (dir) {
case 0: // north
y += steps;
break;
case 1: // east
x += steps;
break;
case 2: // south
y -= steps;
break;
case 3: // west
x -= steps;
break;
}
return [x, y];
}
const stepByStep = (x, y, dir, steps) => {
let pos;
for (let i = 0; i < steps; i++) {
switch (dir) {
case 0: // north
y ++;
break;
case 1: // east
x ++;
break;
case 2: // south
y --;
break;
case 3: // west
x --;
break;
}
pos = `${x}, ${y}`;
if (!visited.has(pos)) {
visited.set(pos, true);
} else {
return {visited: [x, y]};
}
}
return [x, y];
}
console.log('--------------- PART 1 ---------------');
let currDirId = 0; // start with facing north
let [x, y] = [0, 0];
input.forEach((el, i) => {
currDirId = getNextDir(el.substr(0, 1));
[x, y] = getNextPos(x, y, currDirId, +el.substr(1));
// console.log(x,y);
});
console.log(`final position: ${[x, y]}`);
console.log(`i.e. ${Math.abs(x) + Math.abs(y)} blocks away! 🎉`);
console.log('--------------- PART 2 ---------------');
currDirId = 0;
[x, y] = [0, 0];
let visited = new Map();
let pos;
input.find((el, i) => {
currDirId = getNextDir(el.substr(0, 1));
pos = stepByStep(x, y, currDirId, +el.substr(1));
if (Array.isArray(pos)) {
[x, y] = pos;
} else {
[x, y] = pos.visited;
return true;
}
});
console.log(`first position visited twice: ${[x, y]}`);
console.log(`i.e. ${Math.abs(x) + Math.abs(y)} blocks away! 🎉`);