Skip to content

Instantly share code, notes, and snippets.

@kjvalencik
Created January 6, 2014 00:28
Show Gist options
  • Save kjvalencik/8276162 to your computer and use it in GitHub Desktop.
Save kjvalencik/8276162 to your computer and use it in GitHub Desktop.
Coin flip probability
// You have 1,024 coins. One of those coins is double headed,
// but the rest are fair. You pick a coin at random and flip
// it 10 times and get 10 heads. What is the probability that
// the next flip will be heads?
// Constants
var TOTAL_COINS = 1024,
NUM_DOUBLE = 1,
NUM_FLIPS = 10,
PROB_FAIR = .5,
PROB_DOUBLE = 1,
NUM_TRIALS = 10000000;
// Functions
var flipCoin, chooseCoin, isAllHeads, runTrial, runExperiment;
// Results
var allHeadsUntilLast = 0,
allHeads = 0,
totalDoubleHeaded = 0;
// True is heads, false is tails
flipCoin = function (coin) {
var prob = PROB_FAIR;
if (coin < NUM_DOUBLE) {
prob = PROB_DOUBLE;
}
return Math.random() < prob;
};
chooseCoin = function () {
return Math.floor(Math.random() * TOTAL_COINS);
};
isAllHeads = function (results) {
return results && !(results & (results + 1));
};
runTrial = function () {
var coin = chooseCoin(),
results = 1,
i;
// Flip n + 1 times
for (i = 0; i <= NUM_FLIPS; i += 1) {
results = (results << 1) + flipCoin(coin);
}
totalDoubleHeaded += coin < NUM_DOUBLE;
allHeads += isAllHeads(results);
allHeadsUntilLast += isAllHeads(results >> 1);
};
runExperiment = function () {
var i = 0;
for (i = 0; i < NUM_TRIALS; i += 1) {
runTrial();
}
console.log("Flips per trial: " + NUM_FLIPS);
console.log("Total trials: " + NUM_TRIALS);
console.log("Number of trials with " + NUM_FLIPS + " heads: " + allHeadsUntilLast);
console.log("Number of trials with " + (NUM_FLIPS + 1) + " heads: " + allHeads);
console.log("Number of times picked double headed coin: " + totalDoubleHeaded);
console.log("Given " + NUM_FLIPS + " heads, probability next flip is heads: " + (100 * allHeads / (allHeadsUntilLast || 1)) + "%" );
};
runExperiment();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment