204k views
2 votes
Given main() and gvcoin class, complete function consecutive_heads() that counts and returns the number of flips taken to achieve a desired number of consecutive heads without a tails. function consecutive_heads() has a gvcoin object and an integer representing the desired number of consecutive heads without a tails as parameters.

note: for testing purposes, a gvcoin object is created in the main() function using a pseudo-random number generator with a fixed seed value. the program uses a seed value of 15 during development, but when submitted, a different seed value will be used for each test case.
ex: if the gvcoin object is created with a seed value of 15 and the desired number of consecutive heads is 5, then the function consecutive_heads() returns 16 and the program outputs:

1 Answer

5 votes

Answer:

Here is a possible implementation of the consecutive_heads() function based on the given instructions:

Step-by-step explanation:

#include <iostream>

#include <cstdlib>

#include <ctime>

class gvcoin {

public:

gvcoin();

bool flip();

private:

int heads_in_a_row;

};

gvcoin::gvcoin() {

heads_in_a_row = 0;

std::srand(std::time(nullptr)); // seed the random number generator

}

bool gvcoin::flip() {

bool is_heads = std::rand() % 2; // generate a random 0 or 1

if (is_heads) {

heads_in_a_row++;

} else {

heads_in_a_row = 0;

}

return is_heads;

}

int consecutive_heads(gvcoin coin, int num_heads) {

int num_flips = 0;

while (coin.heads_in_a_row < num_heads) {

coin.flip();

num_flips++;

}

return num_flips;

}

int main() {

const int SEED = 15;

std::srand(SEED);

gvcoin coin;

int num_heads = 5;

int num_flips = consecutive_heads(coin, num_heads);

std::cout << "It took " << num_flips << " flips to get " << num_heads << " consecutive heads." << std::endl;

return 0;

}

User Fili
by
9.1k points