adventofcode-2018/08/part2.js

30 lines
794 B
JavaScript
Raw Normal View History

2018-12-08 20:34:24 +00:00
var input = require("fs").readFileSync("input.txt").toString().replace("\n", "");
var nums = input.split(" ").map(a=>(parseInt(a)));
function parseTree(ints){
var numChildren = ints[0];
var numMeta = ints[1];
var children = [];
var i = 0;
while(numChildren > 0){
var childParsed = parseTree(ints.slice(2 + i));
i += childParsed[1].length;
children.push(childParsed[0]);
numChildren--;
}
return [{children: children, meta: ints.slice(2+i, 2+i+numMeta)}, ints.slice(0, 2+i+numMeta)]
}
function nodeValue(node){
var total = 0;
if(node.children.length){
return node.meta.map(a=>(a-1)).map(a=>(node.children[a])).filter(a=>(a)).map(n=>(nodeValue(n))).reduce((a,b)=>(a+b), 0);
}
else{
return node.meta.reduce((a,b)=>(a+b));
}
}
console.log(nodeValue(parseTree(nums)[0]));