-3

I'm facing a problem with this question:

Write a function void:

bool tossCoin (bool& flag);

The function returns true to indicate head (45% chance), false for tail (45% chance). There is 10% chance that the toss will fail, example not landing on a face; if this happens the flag is set to false, and the caller must call the function again (toss the coin again).

Test the function with a program that prompts the user for his/her choice (0 tail, 1 head) then calls the function to find if the user will win or not. If the flag is set to false by the function you must print a message that indicates re-tossing the coin is required,

Hint: you have to use rand() functions

My problem is I don't know how to begin approaching this question and how to do it correctly?

1 Answers1

0

So, basically you need a method that can give you a random with distribution 45% - 45% - 10%. You can do it easily with the following algorithm:

int a = rand() % 100;
if (a < 45)
    return "head";
if (a >= 45 && a < 90)
    return "tail";
else
    return "fail";

But this is a very bad algorithm, because the distribution is not nicely shuffled (you have a huge interval of the same values). So, you can improve it by using the following algorithm:

  1. Let 0 = head, 1 = tail and 2 = fail. Generate an array of 100 elements: the first 45 elements are 0, the following 45 elements are 1 and the last 10 elements are 2;
  2. Randomly shuffle your array, you can do this by using method std::random_shuffle(), or you can write your own shuffle using rand(), the detailed algorithms is described here.
  3. Now you have an array with nicely shuffled elements, put it into an constant array, and you can use it in your function.
Community
  • 1
  • 1
Chan Kha Vu
  • 9,834
  • 6
  • 32
  • 64
  • Certainly, I have tried approaching it according to the first step in the algorithm, however I was stuck in the rest of it. I don't know how to deal with arrays and rand() functions.. – Omar Elgafri May 03 '15 at 15:52