mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Add solutions to day 12 in javascript.
This commit is contained in:
@@ -18,7 +18,7 @@ The current plan, in no particular order:
|
||||
- [x] Kotlin - [Day 10](./day-10/solution.kt)
|
||||
- [x] Lex - [Day 09](./day-09/solution.l)
|
||||
- [x] Matlab - [Day 06](./day-06)
|
||||
- [ ] Node.js
|
||||
- [x] Node.js - [Day 12](./day-12/solution.js)
|
||||
- [ ] Objective C
|
||||
- [x] Perl - [Day 05](./day-05/solution.pl)
|
||||
- [ ] PHP
|
||||
|
||||
2000
2017/day-12/input.txt
Normal file
2000
2017/day-12/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
70
2017/day-12/solution.js
Normal file
70
2017/day-12/solution.js
Normal file
@@ -0,0 +1,70 @@
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user