Click here to Skip to main content
15,889,484 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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
Comments
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++.

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!
 
Share this answer
 
1) Choose your language.
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900