Skip to content

Instantly share code, notes, and snippets.

@devNoiseConsulting
Created January 3, 2018 03:24
Show Gist options
  • Select an option

  • Save devNoiseConsulting/06fd0c7b75446e1c365330b1ddbc21dc to your computer and use it in GitHub Desktop.

Select an option

Save devNoiseConsulting/06fd0c7b75446e1c365330b1ddbc21dc to your computer and use it in GitHub Desktop.
Digital Plumber - Advent of Code - 20171212
let populateTree = function(nodesList) {
let tree = nodesList
.split('\n')
.map(p => {
let [node, children] = p.split(' <-> ');
if (children) {
children = children.split(', ');
}
return {
id: parseInt(node.trim()),
children: children
};
})
.reduce((acc, n, i) => {
acc.set(n.id, n);
return acc;
}, new Map());
let keys = Array.from(tree.keys());
keys.forEach(k => {
let parentNode = tree.get(k);
if (parentNode.children) {
let childKeys = parentNode.children;
parentNode.children = childKeys.map(c => tree.get(parseInt(c)));
} else {
parentNode.children = [];
}
});
return tree;
};
let getGroupSize_1 = function(startNode, tree) {
let visited = [];
tree.forEach(function(value, key) {
visited[key] = false;
});
let descendTree = function(node) {
if (!visited[node.id]) {
visited[node.id] = true;
node.children.forEach(n => descendTree(n));
}
};
descendTree(startNode);
return visited.filter(v => v).length;
};
let getGroupSize = function(startNode, tree) {
return getGroup(startNode, tree).length;
};
let getGroup = function(startNode, tree) {
let visited = [];
tree.forEach(function(value, key) {
visited[key] = false;
});
let descendTree = function(node) {
if (!visited[node.id]) {
visited[node.id] = true;
node.children.forEach(n => descendTree(n));
}
};
descendTree(startNode);
return visited.reduce((acc, n, i) => {
if (n) {
acc.push(i);
}
return acc;
}, []);
};
let findNumberOfGroups = function(tree) {
let visited = [];
tree.forEach(function(value, key) {
visited[key] = -1;
});
tree.forEach(function(node, key) {
if (visited[key] == -1) {
let descendants = getGroup(node, tree);
descendants.forEach(v => {
if (visited[v] == -1) {
visited[v] = key;
}
});
}
});
return visited.filter((v, i, arr) => arr.indexOf(v) == i).length;
};
let test = `0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5`;
test = populateTree(test);
let result = getGroupSize(test.get(0), test);
console.log(result);
result = findNumberOfGroups(test);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment