Last active
February 24, 2020 14:31
-
-
Save Vicfred/3a1177406db5cb5b4ef758c5e04769bd to your computer and use it in GitHub Desktop.
how many flips until n heads
This file contains 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
// How many times do you have to flip a coin | |
// to get n heads? | |
#include <random> | |
#include <iostream> | |
int main() { | |
std::random_device rd; | |
std::mt19937 gen(rd()); | |
std::uniform_int_distribution<> dis(0,1); | |
long double expected = 0.0L; | |
int heads = 0; | |
int trials = 0; | |
int MAXN = 1e6; | |
int HEADS = 2; | |
for(int i = 0; i < MAXN; ++i) { | |
trials = 0; | |
heads = 0; | |
while(heads < HEADS) { | |
if(dis(gen)) | |
++heads; | |
else | |
heads = 0; | |
++trials; | |
} | |
std::cout << trials << std::endl; | |
expected += (long double)trials; | |
} | |
std::cout << (long double)(expected/MAXN) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment