-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.js
executable file
·71 lines (55 loc) · 1.18 KB
/
solution.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
#!/usr/bin/env node
const stdin = process.openStdin();
let content = '';
Set.prototype.union = function(setB) {
var union = new Set(this);
for (var elem of setB) {
union.add(elem);
}
return union;
}
function parseConnections(data) {
let connections = {};
data.split("\n").forEach(line => {
if (!line) {
return;
}
let from, to;
[from, to] = line.split(" <-> ");
connections[from] = to.split(", ");
});
return connections;
}
function getConnected(from, connections) {
let todo = [from];
let connected = new Set(todo);
for (let cur = 0; cur < todo.length; ++cur) {
if (!connections[todo[cur]]) {
continue;
}
connections[todo[cur]].forEach(n => {
if (!connected.has(n)) {
connected.add(n);
todo.push(n);
}
});
}
return connected;
}
stdin.addListener('data', d => {
content += d.toString();
});
stdin.addListener('end', () => {
let connections = parseConnections(content);
let connected = getConnected("0", connections);
console.log(connected.size);
let groups = 1;
for (let n in connections) {
if (connected.has(n)) {
continue;
}
connected = connected.union(getConnected(n, connections));
++groups;
}
console.log(groups);
});