The Yahoo function returns a probability of 0, 1.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.