I'm trying to compute the probability of rolling a certain dice total with an unknown number of dice. Below is a brute force example for 5 dice, hence the 5 loops. I feel like there is a recursive answer here that I can't put my finger on that would work for different numbers of dice.
function computeDiceOdds(dice, desired_result, sides = 6) {
var successes = 0;
for (let a = 1; a <= sides; a++ ) {
for (let b = 1; b <= sides; b++) {
for (let c = 1; c <= sides; c++) {
for (let d = 1; d <= sides; d++) {
for (let e = 1; e <= sides; e++) {
if ((a + b + c + d + e) == desired_result) {
successes++;
}
}
}
}
}
}
return successes.toString() + " / " + Math.pow(sides, dice).toString();
}
console.log(computeDiceOdds(5, 21)); // "540 / 7776"