Advertisement
BLUuuE

Coin Flip

Oct 8th, 2015
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3. #include <limits>
  4. #include <cmath>
  5. using std::cout; using std::cin; using std::endl;
  6.  
  7. //flip the coin
  8. inline int flip()       //heads = 0, tails = 1
  9. {
  10.     return rand() % 2;
  11. }
  12.  
  13. //compares two arrays to see if they're equal
  14. template <size_t N, typename T>
  15. bool isSequenceEqual(T (&seq1)[N], T (&seq2)[N])
  16. {
  17.     int count = 0;
  18.     for (int i = 0; i < N; i++)
  19.     {
  20.         if (seq1[i] == seq2[i])
  21.             count++;
  22.     }
  23.     return count == N;      //if count is equal to N then the arrays are equal; else they aren't
  24. }
  25.  
  26. //function that returns number of coin flips needed to get desiredSeq[] -> nine heads in a row...
  27. unsigned long long Flips()
  28. {
  29.     const int FLIPS = 9;                //max amount of flips
  30.     int sequence[FLIPS] = { 0 };        //random sequence generated by flip()
  31.     int desiredSeq[FLIPS] = { 0 };      //the sequence we want; in this case, all heads
  32.     unsigned long long times = 0LL;     //amount of times the coin has been flipped
  33.  
  34.     do {
  35.         for (int flips = 0; flips < FLIPS; flips++)     //flip the coin 9 times...
  36.             sequence[flips] = flip();
  37.  
  38.         times++;
  39.     } while (!isSequenceEqual(sequence, desiredSeq));
  40.     return times;
  41. }
  42.  
  43. int main()
  44. {
  45.     srand(time(NULL));      //seed rand(), so we get a "random" number from it...
  46.  
  47.     {   //curly brackets to make my typedef only accessible from within
  48.         typedef unsigned long long ull;
  49.         ull sum = 0;                //the accumulative total of the amount of times the coin has to be flipped to get nine heads...
  50.         double noOfFlips = 1e5;     //number of times to run the Flips() function; higher value = more accurate but longer to calculate...
  51.  
  52.         for (ull i = 0; i < noOfFlips; i++)
  53.             sum += Flips();
  54.  
  55.         cout << "The average number of flips is " << round(sum / noOfFlips) << endl;        //round() from cmath; rounds the number...;
  56.     }
  57.  
  58.     cout << "Press enter to exit...";
  59.     getchar();
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement