Skip to content

Instantly share code, notes, and snippets.

@scorta
Last active April 23, 2020 09:00
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 scorta/9b55621b119fcdec85b49a5583b59a1c to your computer and use it in GitHub Desktop.
Save scorta/9b55621b119fcdec85b49a5583b59a1c to your computer and use it in GitHub Desktop.
// Flip coin until we get 3 consecutive "Tail" or "Head"
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <unordered_map>
using namespace std;
enum class coin_state {head, tail};
unordered_map<coin_state, string> coin_state_ref {
{coin_state::head, "H"},
{coin_state::tail, "T"}
};
ostream& operator<<(ostream& os, const coin_state& cs) {
os << coin_state_ref[cs];
}
int main() {
srand(time(NULL)); // Should have used a better random method, but too lazy
int no_of_experiment;
double no_of_flip_total = 0;
cout << "How many times do you want to do experiment? ";
cin >> no_of_experiment;
for (int run = 1; run <= no_of_experiment; ++run) {
cout << "========= Experiment number: " << run << " =========\n";
int no_of_flip = 0;
for (int count_tail = 0, count_head = 0; count_head < 3 && count_tail < 3;) {
++no_of_flip;
auto state = rand() % 2 == 0 ? coin_state::head : coin_state::tail;
cout << state << " ";
if (state == coin_state::tail) {
++count_tail;
count_head = 0;
} else {
++count_head;
count_tail = 0;
}
}
no_of_flip_total += no_of_flip;
cout << "\nNeed " << no_of_flip << " flip(s)\n";
}
cout << "==================\nAverage: " << no_of_flip_total / no_of_experiment << " flip(s)";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment