Last active
December 12, 2017 13:04
-
-
Save incon/6a8621a008f3e1dae2096893dfa6a219 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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