Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <ctime>
- #include <limits>
- #include <cmath>
- #include <thread>
- using std::cout; using std::cin; using std::endl;
- using std::thread;
- //flip the coin
- inline int flip() //heads = 0, tails = 1
- {
- return rand() % 2;
- }
- //compares two arrays to see if they're equal
- template <size_t N, typename T>
- bool isSequenceEqual(T (&seq1)[N], T (&seq2)[N])
- {
- int count = 0;
- for (int i = 0; i < N; i++)
- {
- if (seq1[i] == seq2[i])
- count++;
- }
- return count == N; //if count is equal to N then the arrays are equal; else they aren't
- }
- //function that returns number of coin flips needed to get desiredSeq[] -> nine heads in a row...
- unsigned long long Flips()
- {
- const int FLIPS = 9; //max amount of flips
- int sequence[FLIPS] = { 0 }; //random sequence generated by flip()
- int desiredSeq[FLIPS] = { 0 }; //the sequence we want; in this case, all heads
- unsigned long long times = 0LL; //amount of times the coin has been flipped
- do {
- for (int flips = 0; flips < FLIPS; flips++) //flip the coin 9 times...
- sequence[flips] = flip();
- times++;
- } while (!isSequenceEqual(sequence, desiredSeq));
- return times;
- }
- int avgFlips()
- {
- typedef unsigned long long ull;
- ull sum = 0; //the accumulative total of the amount of times the coin has to be flipped to get nine heads...
- double noOfFlips = 1e5; //number of times to run the Flips() function; higher value = more accurate but longer to calculate...
- for (ull i = 0; i < noOfFlips; i++)
- sum += Flips();
- cout << "The average number of trials needed to get 9 heads is " <<
- round(sum / noOfFlips) << endl; //round() from cmath; rounds the number...;
- return round(sum / noOfFlips);
- }
- int main()
- {
- srand(time(NULL)); //seed rand(), so we get a "random" number from it...
- //change this to whatever you want; I have an i7 which has multithreading so I set it at 8...
- const int numOfThreads = 8;
- thread threads[numOfThreads];
- cout << "Creating threads...\n";
- /*Create threads*/
- for (int t = 0; t < numOfThreads; t++)
- threads[t] = thread(avgFlips);
- cout << "Threads created.\n" <<
- "Running threads...\n\n";
- /*Wait for threads to finish*/
- for (int r = 0; r < numOfThreads; r++)
- threads[r].join();
- cout << "Press enter to exit...";
- getchar();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement