Created
July 1, 2022 19:20
-
-
Save PhilippMeissner/f72a9f7f6888c4f6e6bc8e086849d22d to your computer and use it in GitHub Desktop.
Coinflip calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const HEADS = 'heads'; | |
const TAILS = 'tails'; | |
const DESIRED_STREAK_COUNT = 10; | |
const DESIRED_RESULT = HEADS; | |
function start() { | |
let attempts = 1; | |
let totalFlips = 0; | |
let streakCount = 0; | |
let done = false; | |
while (!done) { | |
const result = coinFlip(); | |
totalFlips++; | |
if (result === DESIRED_RESULT) { | |
// Yay, desired result. | |
streakCount++; | |
} else { | |
// Start all over. | |
streakCount = 0; | |
attempts++; | |
} | |
if (streakCount === DESIRED_STREAK_COUNT) { | |
// We are done | |
done = true; | |
} | |
} | |
return { attempts, totalFlips }; | |
} | |
function coinFlip() { | |
return Math.round(Math.random()) === 0 ? HEADS : TAILS; | |
} | |
const TOTAL_RUNS = 500000; | |
let globalAttempts = 0; | |
let globalTotalFlips = 0; | |
for (let i = 0; i < TOTAL_RUNS; i++) { | |
const { attempts, totalFlips } = start(); | |
globalAttempts += attempts; | |
globalTotalFlips += totalFlips; | |
} | |
console.log(`${TOTAL_RUNS}`); | |
console.log(`On average ${globalAttempts / TOTAL_RUNS} attempts per run.`); | |
console.log(`On average ${globalTotalFlips / TOTAL_RUNS} flips per run.`); | |
// Some results: | |
// 2500 | |
// On average 1034.838 attempts per run. | |
// On average 2066.8296 flips per run. | |
// 5000 | |
// On average 1002.8526 attempts per run. | |
// On average 2003.4454 flips per run. | |
// 10000 | |
// On average 1028.1834 attempts per run. | |
// On average 2054.4075 flips per run. | |
// 20000 | |
// On average 1029.70735 attempts per run. | |
// On average 2057.75995 flips per run. | |
// 50000 | |
// On average 1024.1241 attempts per run. | |
// On average 2046.05932 flips per run. | |
// 100000 | |
// On average 1024.08843 attempts per run. | |
// On average 2046.14881 flips per run. | |
// 200000 | |
// On average 1021.128585 attempts per run. | |
// On average 2040.19978 flips per run. | |
// 200000 | |
// On average 1025.70776 attempts per run. | |
// On average 2049.322875 flips per run. | |
// 200000 | |
// On average 1026.474355 attempts per run. | |
// On average 2050.808345 flips per run. | |
// 500000 | |
// On average 1023.405016 attempts per run. | |
// On average 2044.827366 flips per run. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment