Skip to content

Instantly share code, notes, and snippets.

@wavebeem
Created February 5, 2022 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wavebeem/fa2ffe22f4d35cca177e94653bafbded to your computer and use it in GitHub Desktop.
Save wavebeem/fa2ffe22f4d35cca177e94653bafbded to your computer and use it in GitHub Desktop.
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