http://m.blog.csdn.net/blog/u012605629/40406577
Construct a random generator
2014-10-23 Read 83 comments 0
2. A random generator is known, the probability of generating 0 is P, the probability of generating 1 is 1-p,
Now you want to construct a generator,
So that it constructs 0 and 1 probability are 1/2;
Constructs a generator, makes it constructs 1, 2, 3 probability all is 1/3;
Constructs a generator, makes it constructs 1, 2, 3 、... n probability are 1/n, requires the least complexity.
/*2. A random generator is known to generate 0 probability is p, the probability of generating 1 is 1-p, now you want to construct a generator, so that it constructs 0 and 1 of the probability of 1/2; construct a generator, so that it constructs 1, 2, 3 probability of 1/3, ..., constructs a generator, makes it constructs 1, 2, The probability of 3 、... n is 1/n, which requires the least complexity. Idea: Due to the need to produce 1/2, and 1 bits 0, or 1 bit 1 can not generate equal probability, therefore, consider expanding the random number to 2-bit: p*p01 p* (1-p) (1-p) *p11 (1-p) * (1-p) with the above analysis know, 01 and 10 are equal probabilities, so we only need to produce 01 and 10 on the line. So you can, encounter 00 and 11 is discarded, only records 01 and 10. can make, 01 means that the 0,10 is 1, then the probability 1/2 will produce 0 and 1. For N=2, a one-time generation of two numbers, that 01 means that 0,10 represents 1, others give up, their probability is p* (1-p); for n=3, generate three numbers at a time, 001 means 0,010 means 1,100 means 2, others give up, their probabilities are p*p* ( 1-P); for N=4, a one-time generation is a number, that 0001 means that the 0,0010 means that the 1,0100 means that the 2,1000 represents 3, the others give up, their probability is p*p*p* (1-p), 5 For example, at this time we take x=2, because C (2x,x) =c (4,2) =6 is the smallest x than 5, at this point we are a one-time generation of the 4-bit binary, the 1 appear number is not 2 are discarded, the remaining six: 0011,0101,0110,1001,1010,1100, take the smallest 5, that is discarded 1100, Then we numbered 1 to 5 for the first 5, and the probability is p*p* (1-p) * (1-p) equals. The key is to find the smallest x, so that C (2x,x) >=n can improve the search efficiency. Because C (n,i) is the largest in the I close to N/2 place, at this time I have a larger ratio of the sequence used to generate, in other words, to be thrown away less, to avoid a large number of generation of the drop sequence to slow down the rate of generation, in fact, I have X is to make the sequence I have to generate the probability of equal For example, the probability of C (2x,x) is [P (1-p)]^x, the reciprocal sample space to ensure that the corresponding sample of each value obtained and other probabilities. */
Construct a random generator