Question: A function Foo can return 0, 1 with a probability of 3: 2. Now it is required to write a fun2 and return 0, 1 with an equi probability.
This Is What Baidu says when I see an interview question.
One function fun can return values 0 and 1. The probability of returning values 0 and 1 is 1/2. How can we use this function to get another function fun2 so that fun2 can only return values 0 and 1, the probability of returning 0 is 1/4, and the probability of returning 1 is 3/4. (What if the probability of returning 0 is 0.3 and the probability of returning 1 is 0.7)
On the internet to see a classmate's answer, written very good http://www.haogongju.net/art/1665092
Solution:
0, 1 is randomly generated, which can be interpreted as a binary system.
A = fun () * 2 ^ 4 + fun () * 2 ^ 3 + fun () * 2 ^ 2 + fun () * 2 ^ 1 + fun () equi-probability generation of all numbers from 0 to 31
After removing 30 and 31, A % 3 output is made between 0 and 29.
In fact, the allocation of these 30 numbers makes one account for 3 copies and one account for 7 copies. According to the algorithm of that classmate, 10 of the 30 numbers take the Modulo for 3 and 0, 20 of the non-0 values, the ratio is, but it is a little worse. It should be after the simplification. Therefore, if the modulo is 0, you need to give the other party one, and simply return the 0 value to the other party, may generate 3: 7.
It is easier to return, so we can get four values 0-3. If the value is 0, we can return 0, 1, 2, and 3, and return 1. This method is more direct.
Back to our problem, where the probability returned by foo is not equal to 0 and 1, and how to solve the problem.