Skip to content

Instantly share code, notes, and snippets.

@draeton
Created September 11, 2011 01:02
Show Gist options
  • Save draeton/1209028 to your computer and use it in GitHub Desktop.
Save draeton/1209028 to your computer and use it in GitHub Desktop.
Run a number of tests on a set of dice to see what the average number of rolls is required to have them all land on the first side (represented here with a "0"). Returns the average.
(function (window) {
// Return a random integer from 0 to `d`
function r(d) {
return Math.round(Math.random() * --d);
}
// Roll the dice. Returns a string of integers to represent which
// side each die fell on ("0" is the first side).
//
// `m` is the number of dice to roll
// `d` is the number of sides each die has
function roll(m, d) {
return new Array(m).join().split(",").map(function () {
return r(d);
}).join("");
}
// Run one test of a set of dice. This runs until the `roll`
// returns a string that matches `s`. Returns the number of
// rolls.
//
// `s` is a string of zeros, with length `m`
// `m` is the number of dice to roll
// `d` is the number of sides each die has
function test(s, m, d) {
var i = 0;
while (++i) {
if (roll(m, d) === s) {
return i;
}
}
}
// Run a number of tests on a set of dice to see what the average
// number of rolls is required to have them all land on the first
// side (represented here with a "0"). Returns the average.
//
// `m` is the number of dice to roll in each test
// `n` is the number of tests to run
// `d` is the number of sides each die has
function testDice(m, n, d) {
var i, s = new Array(m + 1).join("0"), total = 0;
for (i = 0; i < n; i++) {
total += test(s, m, d);
}
return total / n;
}
window.testDice = testDice;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment