Skip to content

Instantly share code, notes, and snippets.

@incon incon/AoC-2017-day12.js
Last active Dec 12, 2017

Embed
What would you like to do?
const input = require("fs").readFileSync("day12-input.txt", "UTF-8");
pairs = {};
input.split("\n").forEach(row => {
split = row.split(" <-> ");
split[1] = split[1].split(", ");
pairs[split[0]] = split[1];
});
count = 0;
seen = [];
program = {};
match = 0;
Object.keys(pairs).forEach(key => (program[key] = 0));
function group() {
Object.keys(pairs).forEach(key => {
if (key === match) {
program[key] = 1;
seen.push(key);
}
seen = [];
if (find(pairs[key]) > 0) {
program[key] = 1;
}
});
}
function find(childern) {
c = 0;
childern.forEach(child => {
if (child == match) {
c++;
}
if (seen.indexOf(child) === -1) {
seen.push(child);
c += find(pairs[child]);
}
});
return c;
}
function reduceHash() {
matched = Object.keys(program).filter(key => program[key] === 1);
matched.forEach(id => {
delete pairs[id];
delete program[id];
});
}
group();
groups = 1;
reduceHash();
console.log("Part 1:", matched.length);
while (Object.keys(program).length) {
match = Object.keys(program).filter(key => program[key] === 0)[0];
group();
groups++;
reduceHash();
}
console.log("Part 2:", groups);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.