Given a randomly generated integer 1 to 5 function , write a function that can randomly generate integers 1 to 7
Method 1:
Rand5 () *5+rand5 ()to obtain a probability distribution of the number of numbers in [6,30] interval
You can only use the number of 6~26 between the two , mapping to 1~ 7 number
What about ~30 ? Throw it away .
int Rand7 () { int i; while ((I=rand5 () *5+rand5 ()) >); return (I-3)/3;}
The resulting 1~7 probabilities are uniform, but not equal to 1
Method 2:
Generate a 5 binary number with Rand5 ()
If there are 3 bits, then each bit generates a Rand5 (), which is the evenly distributed integer on [0,444] .
Unfortunately , 7 cannot divide the power of 5 evenly, so that 7 segments cannot be evenly divided.
But if the number of digits is large enough, the probability of omission will be quite small.
Similar problems
Known Rand1 () and other probabilities return 0 or 1, try to write a function, etc. returns the integer between [A, b]
In binary notation a and b,
Get the digits of a , The digits of B,
The bitwise generation of the binary number, which is regenerated if the [A, b] range is exceeded
(For the previous question, if the random number generator can generate even-numbered ranges, the RAND1 () can be constructed first, which is the problem later)
Similar problems
Known Rand7 (), Ball rand10 ()
This can be turned into the first question: Construct Rand7 () *7+rand7 (), then filter, then split
Or you can turn Rand7 () first into Rand5 () and Rand2 () andthen combine
int Rand10 () { int T1; int T2; do {T1 =rand7 (); while (T1>5 ); do {T2 =rand7 (); while (T2>2 ); return t1+5 * (T2-1 );}
Promote:
Known RANDK (), Beg randn ()
N is represented by the K- notation, and the first number of bits is required to solve m:
k^m-1=nm=int(m) +1int randn () { while (sum> N) { for (i=0; i<m;++i) bit I of sum=randk ();} }
Understand the key knowledge of this type of problem:
This number is also equal to the probability distribution in the whole domain, such as the probability distribution of each bit
A subset of equal probability distributions [A, b] (for example [A+1,b-1]) is equally equal to the probability distribution, only the probability of the sub-set and not 1, but does not affect the algorithm implementation
Ref:http://www.cnblogs.com/youxin/p/3351213.html
Random number generation problem