-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day12.js
52 lines (46 loc) · 1.17 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
const part1 = (input) => {
let connections = {};
let rows = input.split(/\n+/).forEach(r => {
let [p, cons] = r.split(/\s+<->\s+/);
connections[p] = cons.split(/,\s+/).map(n => n);
});
let seen = [];
const findNeighbours = (p) => {
if (seen.indexOf(p) < 0) {
seen.push(p);
}
connections[p].forEach(c => {
if (seen.indexOf(c) < 0){
findNeighbours(c);
}
});
}
findNeighbours('0');
console.log('A:', seen.length);
};
const part2 = (input) => {
let connections = {};
let rows = input.split(/\n+/).forEach(r => {
let [p, cons] = r.split(/\s+<->\s+/);
connections[p] = cons.split(/,\s+/).map(n => n);
});
let groups = {};
const findNeighbours = (g, p) => {
if (groups[g].indexOf(p) < 0) {
groups[g].push(p);
}
connections[p].forEach(c => {
if (groups[g].indexOf(c) < 0){
findNeighbours(g, c);
}
});
}
for (var k in connections) {
let alreadyGrouped = Object.values(groups).filter(a => a.indexOf(k) >= 0).length;
if (!alreadyGrouped) {
groups[k] = [];
findNeighbours(k, k);
}
}
console.log('B:', Object.values(groups).length);
};