adventofcode-2017/day07/part2.js
2017-12-07 15:07:07 +00:00

58 lines
1.3 KiB
JavaScript

var lines = require("fs").readFileSync("input.txt").toString().split("\n").filter((a)=>(a));
var top = lines[0].split(" ")[0];
var oldtop = "";
while(oldtop != top){
oldtop = top;
for(var line of lines){
if(line.indexOf("->") != -1){
if(line.split(" -> ")[1].split(", ").indexOf(top) != -1){
top = line.split(" ")[0];
}
}
}
}
//console.log(top);
var discs = {};
for(var line of lines){
var disc = {
weight: parseInt(new RegExp("\(([0-9]+)\)").exec(line)[0]),
subweight: 0,
children: []
}
if(line.indexOf("->") != -1){
disc.children = line.split(" -> ")[1].split(", ");
}
discs[line.split(" ")[0]] = disc;
}
function calcsubweight(id){
if(discs[id].children.length == 0){
return discs[id].weight;
}
else{
var childweight = -1;
discs[id].subweight += discs[id].weight;
for(var child of discs[id].children){
discs[child].subweight = calcsubweight(child);
discs[id].subweight += discs[child].subweight;
if(childweight != discs[child].subweight && childweight != -1){
console.log(id, child, childweight, discs[child].subweight);
}
childweight = discs[child].subweight;
}
return discs[id].subweight;
}
}
function debugPrint(id, i){
console.log(i, id, discs[id]);
for(var child of discs[id].children){
debugPrint(child, i+1);
}
}
calcsubweight(top);
debugPrint("wknuyhc", 0);
//console.log(discs);