-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwelve.js
More file actions
72 lines (62 loc) · 1.45 KB
/
Copy pathtwelve.js
File metadata and controls
72 lines (62 loc) · 1.45 KB
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
import { readFile } from 'fs/promises';
const GRAPH = {};
const START = 'start';
const END = 'end';
const fullPaths = [];
// 12ab
async function init() {
const input = await readFile('twelve.txt', 'utf8');
const connections = input.split('\n');
connections.forEach((c) => {
const [from, to] = c.split('-');
add(from, to);
add(to, from);
});
console.log(GRAPH);
for (let next of GRAPH[START]) {
const currentPath = [START, next];
findPath(currentPath, next);
}
console.log(fullPaths.length);
}
function findPath(currentPath, last) {
for (let next of GRAPH[last]) {
if (next === END) {
fullPaths.push([...currentPath, END].join(','));
} else if (next === START) {
} else if (next.toUpperCase() !== next && moreThanOne(currentPath, next)) {
} else if (validPath([...currentPath, next])) {
findPath([...currentPath, next], next);
}
}
}
function moreThanOne(path, node) {
return path.filter((n) => n === node).length >= 2;
}
function validPath(path) {
let num = 0;
let smalls = {};
for (let i = 0; i < path.length; i++) {
const cur = path[i];
if (cur.toUpperCase() !== cur) {
if (smalls[cur]) {
num++;
} else {
smalls[cur] = true;
}
}
if (num >= 2) {
return false;
}
}
return true;
}
function add(from, to) {
if (GRAPH[from]) {
GRAPH[from].add(to);
} else {
GRAPH[from] = new Set();
GRAPH[from].add(to);
}
}
init();