-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6b.js
83 lines (65 loc) · 1.81 KB
/
6b.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
import {readInput} from "./lib.js";
let input = readInput(6).map((line) => line.split(""));
let guardStart = null;
for (let y = 0; y < input.length; y++) {
const line = input[y];
for (let x = 0; x < line.length; x++) {
if (line[x] === "^") {
guardStart = {x, y};
break;
}
}
}
function patrolIsLoop() {
let guard = {...guardStart};
let direction = 0;
const steps = new Set();
// steps.add(`${guard.x},${guard.y}`);
do {
const newGuard = {...guard};
if (direction === 0) {
newGuard.y--;
} else if (direction === 1) {
newGuard.x++;
} else if (direction === 2) {
newGuard.y++;
} else {
newGuard.x--;
}
if (!(newGuard.x >= 0 && newGuard.x < input[0].length && newGuard.y >= 0 && newGuard.y < input.length)) {
return false;
}
if (steps.has(`${newGuard.x},${newGuard.y},${direction}`)) {
return true;
}
const tile = input[newGuard.y][newGuard.x];
if (tile === '#') {
direction = (direction + 1) % 4;
} else {
guard = newGuard;
steps.add(`${guard.x},${guard.y},${direction}`);
}
} while (true);
}
let loops = [];
// input[guardStart.y][guardStart.x - 1] = "#";
// console.log(patrolIsLoop());
//
for (let y = 0; y < input.length; y++) {
const line = input[y];
for (let x = 0; x < line.length; x++) {
if (line[x] === "^") {
continue;
}
if (line[x] === "#") {
continue;
}
input[y][x] = "#";
if (patrolIsLoop()) {
loops.push({x, y});
}
input = readInput(6).map((line) => line.split(""));
}
console.log(y);
}
console.log(loops.length);