-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12.js
100 lines (71 loc) · 1.64 KB
/
day12.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const fs = require("fs");
const obj = {};
fs.readFileSync("day12.txt", { encoding: "utf-8" })
.split("\n")
.filter((x) => Boolean(x))
.map((x) => {
const [from, to] = x.split("-");
if (!obj[from]) {
obj[from] = [];
}
if (!obj[to]) {
obj[to] = [];
}
obj[from].push(to);
obj[to].push(from);
return;
});
const isSmallCave = (string) => {
return /[a-z]/.test(string);
};
const caveSearch = (node, visited, paths) => {
visited.push(node);
if (node === "end") {
paths.push(visited.join`,`);
return;
}
for (const i of obj[node]) {
if (isSmallCave(i) && visited.includes(i)) {
continue;
}
caveSearch(i, [...visited], paths);
}
};
const myFunction = () => {
const paths = [];
caveSearch("start", [], paths);
return paths.length;
};
const value = myFunction();
console.log(value);
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++= //
const caveSearch2 = (node, visited, visitedTwice, paths) => {
visited.push(node);
if (node === "end") {
paths.push(visited.join(","));
return;
}
for (const i of obj[node]) {
if (i === "start") {
continue;
}
if (isSmallCave(i) && visited.includes(i)) {
if (visitedTwice) {
continue;
}
if (visited.filter((x) => x === i).length >= 2) {
continue;
}
caveSearch2(i, [...visited], true, paths);
} else {
caveSearch2(i, [...visited], visitedTwice, paths);
}
}
};
function myFunction2() {
const paths = [];
caveSearch2("start", [], false, paths);
return paths.length;
}
const value2 = myFunction2();
console.log(value2);