52 lines
1.5 KiB
JavaScript
52 lines
1.5 KiB
JavaScript
|
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));
|
||
|
give(bot.low[0], bot.low[1], bot.values[0]);
|
||
|
give(bot.high[0], bot.high[1], bot.values[1]);
|
||
|
bot.values = [];
|
||
|
}
|
||
|
|
||
|
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);
|
||
|
|
||
|
console.log(outputs);
|
||
|
console.log(outputs[0] * outputs[1] * outputs[2]);
|