-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09.js
55 lines (45 loc) · 1.23 KB
/
09.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
const DIRECTIONS = {
D: [0, -1],
L: [-1, 0],
R: [1, 0],
U: [0, 1],
};
function moveKnot(head, knot) {
const xDiff = head[0] - knot[0];
const yDiff = head[1] - knot[1];
// needs to move horizontally
if (Math.abs(xDiff) === 2 && yDiff === 0) {
knot[0] += xDiff / Math.abs(xDiff);
}
// needs to move horizontally
if (Math.abs(yDiff) === 2 && xDiff === 0) {
knot[1] += yDiff / Math.abs(yDiff);
}
// needs to move diagonally
if (
(Math.abs(xDiff) === 2 && Math.abs(yDiff) > 0) ||
(Math.abs(xDiff) > 0 && Math.abs(yDiff) === 2)
) {
knot[0] += xDiff / Math.abs(xDiff);
knot[1] += yDiff / Math.abs(yDiff);
}
}
export function solve(input, knots = 2) {
const tailPositionMap = {};
const positions = Array(knots)
.fill()
.map(() => [0, 0]);
input.split('\n').forEach((move) => {
const [d, steps] = move.split(' ');
const direction = DIRECTIONS[d];
for (let i = 0; i < steps; i++) {
positions[0][0] += direction[0];
positions[0][1] += direction[1];
for (let k = 0; k < knots - 1; k++) {
moveKnot(positions[k], positions[k + 1]);
}
tailPositionMap[positions[knots - 1]] = true;
}
});
return Object.keys(tailPositionMap).length;
}