adventofcode-2016/day10/part1.js

54 lines
1.6 KiB
JavaScript
Raw Normal View History

2016-12-10 22:17:02 +00:00
var input = require("fs").readFileSync("input.txt").toString().replace(/\r/g, "");
var bots = [];
var outputs = [];
input.split("\n").filter((a)=>(a)).forEach((line)=>{
if(line.indexOf("bot") == 0){
var lineData = line.match(/bot ([0-9]+) gives low to ([^ ]+) ([0-9]+) and high to ([^ ]+) ([0-9]+)/);
if(!bots[parseInt(lineData[1])]){
bots[parseInt(lineData[1])] = {};
}
bots[parseInt(lineData[1])].low = [lineData[2], parseInt(lineData[3])];
bots[parseInt(lineData[1])].high = [lineData[4], parseInt(lineData[5])];
}
else{
var lineData = line.match(/value ([0-9]+) goes to bot ([0-9]+)/);
if(!bots[parseInt(lineData[2])]){
bots[parseInt(lineData[2])] = {};
}
if(!bots[parseInt(lineData[2])].values){
bots[parseInt(lineData[2])].values = [];
}
bots[parseInt(lineData[2])].values.push(parseInt(lineData[1]));
}
});
function resolveBot(id){
var bot = bots[id];
bot.values = bot.values.sort((a, b)=>(a - b));
var low = bot.values[0];
var high = bot.values[1];
if((low == 17) && (high == 61)){
console.log("Found", id);
}
bot.values = [];
give(bot.low[0], bot.low[1], low);
give(bot.high[0], bot.high[1], high);
}
function give(type, target, value){
if(type == "bot"){
if(!bots[target].values) bots[target].values = [];
bots[target].values.push(value);
if(bots[target].values.length == 2){
resolveBot(target);
}
}
else{
outputs[target] = value;
}
}
resolveBot(bots.map((a, i)=>{a.id=i; return a;}).filter((a)=>(a.values)).filter((a)=>(a.values.length == 2))[0].id);