function rollDie(sides){
return Math.floor((Math.random() * sides)) + 1;
}
function explodeResult(result, max){
var interimResult = result;
var finalResult = result;
while (interimResult === max){
interimResult = rollDie(max);
finalResult += interimResult;
}
return finalResult;
}
function rollWithAdvantage(sides, totalDice, toKeep, rolls, explode){
var totals = [];
for(var i = 0; i < rolls; i++) {
var results = [];
for(j = 0; j < totalDice; j++){
results.push(rollDie(sides));
}
results.sort((a,b) => b-a);
var keepers = results.slice(0, toKeep);
if(explode){
keepers = keepers.map(result => explodeResult(result, sides));
}
// add 20 sided die to roll total
totals[i] = keepers.reduce((a,b) => a+b) +
(explode ? explodeResult(rollDie(20), 20) : rollDie(20));
}
var size = Math.max.apply(Math, totals);
console.log(size);
counts = Array.apply(null, Array(size)).map(Number.prototype.valueOf,0);
totals.forEach(total => counts[total-1]++);
return counts;
}
var finalResults = [];
finalResults.push(rollWithAdvantage(6, 3, 2, 100000, true));
finalResults.push(rollWithAdvantage(12, 2, 1, 100000, true));
console.log(finalResults);