Created
February 5, 2022 20:55
-
-
Save wavebeem/fa2ffe22f4d35cca177e94653bafbded to your computer and use it in GitHub Desktop.
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
function chanceToWin() { | |
return Math.random() < 0.5; | |
} | |
function howManyMatchesToGoFlawless() { | |
let matches = 0; | |
let wins = 0; | |
while (wins < 7) { | |
if (chanceToWin()) { | |
wins++; | |
} else { | |
wins = 0; | |
} | |
matches++; | |
} | |
return matches; | |
} | |
function howManyMatchesToGoFlawlessOnAverage() { | |
const n = 2e6; | |
return iterAverage(iterMap(iterRange(n), howManyMatchesToGoFlawless)); | |
} | |
function* iterRange(n) { | |
for (let i = 0; i < n; i++) { | |
yield i; | |
} | |
} | |
function* iterMap(items, fn) { | |
for (const x of items) { | |
yield fn(x); | |
} | |
} | |
function iterAverage(items) { | |
let sum = 0; | |
let n = 0; | |
for (const x of items) { | |
sum += x; | |
n++; | |
} | |
return sum / n; | |
} | |
console.log(howManyMatchesToGoFlawlessOnAverage()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment