Tuesday, 28 April 2015

C++ Flip a Coin Problem: Program to Flip a Coin (until you get 3 "heads" in a row)

Flip a coin


The same problem is also called "The consecutive heads problem"

Problem Overview: Write a program that simulates flipping a coin repeatedly and continues until three consecutive heads are tossed.
At that point, your program should display the total number of coin flips that were made.

The following is one possible sample run of the program:
Heads..
Tails..
Tails..
Heads..
Heads..
Heads..
It took 6 tosses to get 3 consecutive heads.
Press any key to continue . . .

Note: In the below code the output will always be changed because of random number generator function i.e., rand() .

Code: FileName: "FlipTheCoin.cpp"

#include <iostream>
#include <string>
using namespace std;
enum { Head, Tail };
int flip();
string label(int);
int flip()
{
    return rand()%2 == 0 ? Head : Tail;
}
string label(int value)
{
    return (value == Head ? "Head.." : "Tail..");
}
   int main (int argc, const char * argv[])
{
    // seed PRNG
    srand( (unsigned int)time(NULL) );   
    // declare variables
    int headCount = 0, tossCount = 0;
    int flipValue = -1;



    // run loop
    while ( headCount < 3 )
    {
        flipValue = flip();    
        headCount = (flipValue == Head) ? (headCount + 1) : 0;
        ++tossCount;
        cout << label(flipValue) << endl;
    }
    // print answers
    cout << "It took " << tossCount << " tosses to get " << headCount << " consecutive heads." << endl;
    system("pause");
    return 0;
}


0 comments:

Post a Comment