Skip to content

Instantly share code, notes, and snippets.

@henhal
Created April 20, 2020 12:33
Show Gist options
  • Save henhal/8e1af97ab0ead15e245a4bbe4ddd6b8d to your computer and use it in GitHub Desktop.
Save henhal/8e1af97ab0ead15e245a4bbe4ddd6b8d to your computer and use it in GitHub Desktop.
Yatzy probability counter
function factorial(k) {
return (k === 0) ? 1 : k * factorial(k - 1);
}
function binomial(n, k) {
return factorial(n) / factorial(k) / factorial(n - k);
}
// Probability of k sixes from n dice
function prob(n, k) {
return Math.pow(1 / 6, k) * Math.pow(5 / 6, n - k) * binomial(n, k);
}
// Probability of getting Yatzy with n dice and t turns
function probSixesYatzy(n, t) {
if (n === 0) {
return 1;
}
if (t === 0) {
return 0;
}
let sum = 0;
// If last turn, no need to look at any other case than getting all the remaining sixes
for (let k = (t === 1 ? n : 0); k <= n; k++) {
sum += prob(n, k) * probSixesYatzy(n - k, t - 1);
}
return sum;
}
const [nbrDice, nbrTurns] = process.argv.slice(2).map(x => parseInt(x));
const p = probSixesYatzy(nbrDice, nbrTurns);
console.log(`Sum: ${p} (${p * 100} %)`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment