Click here to Skip to main content
14,039,029 members
Rate this:
 
Please Sign up or sign in to 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++.
Rate this: bad
 
good
Please Sign up or sign in to vote.

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!
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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.
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190425.1 | Last Updated 8 Sep 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100