14,039,029 members
See more:
Using the C++ random number generator rand(), implement a biased coin that outputs 1 with probability p and 0 with probability 1–p. Do not seed the random number generator within the function you will be implementing!

What I have tried:

I have tried this to generate 0 and 1:

float output=rand()%2;
Posted
Updated 8-Sep-18 5:57am
Richard MacCutchan 8-Sep-18 11:53am

You have add the tags for C, Java and Python. But your question clearly tells you to use C++.

## Solution 1

Read the question carefully: it requires you to produce a BIASED coin: one that returns more 0's than 1's or vice versa, dependent on the probability given in `p`

So, instead of using 2 which gives you a straight 50:50, you need to use the value of `p` to bias your results. Since `p` is a floating point value between 0 and 1 and `rand` always returns an integer, you are going to have to get sneaky.
I'd start by doing two tests: p = 0 (in which case return 0) and p = 1 (in which case return 1). If they both fail, then generate a random number and multiply it by p. If the result is greater than half the maximum value `rand` can return in your system then return a 1, otherwise return a 0.

But this is your homework, not mine - so I'll give you no code!

## Solution 2

2) study how rand is working in that language.
Quote:
implement a biased coin that outputs 1 with probability p and 0 with probability 1–p.

the important word is 'biased'. This imply a 2 step drawing.
Say the odds are 0.33 and 0.67.
- draw a random number
- check the random against odds and decide of the result.

We do not do your HomeWork.
So just a few hints.

Top Experts
Last 24hrsThis month
 OriginalGriff 235 Patrice T 130 Maciej Los 128 CHill60 100 Richard MacCutchan 70
 OriginalGriff 3,664 Maciej Los 1,459 Dave Kreskowiak 1,345 Patrice T 1,248 Gerry Schmitz 1,177