An interview question: About Probability

前端 未结 10 1465
清酒与你
清酒与你 2021-01-29 21:14

An interview question:

Given a function f(x) that 1/4 times returns 0, 3/4 times returns 1. Write a function g(x) using f(x) that 1/2 times returns 0, 1/2 times returns

10条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 21:35

    Since each return of f() represents a 3/4 chance of TRUE, with some algebra we can just properly balance the odds. What we want is another function x() which returns a balancing probability of TRUE, so that

    function g() {    
        return f() && x();
    }
    

    returns true 50% of the time.

    So let's find the probability of x (p(x)), given p(f) and our desired total probability (1/2):

    p(f) * p(x) =  1/2
    3/4  * p(x) =  1/2
           p(x) = (1/2) / 3/4
           p(x) =  2/3
    

    So x() should return TRUE with a probability of 2/3, since 2/3 * 3/4 = 6/12 = 1/2;

    Thus the following should work for g():

    function g() {
        return f() && (rand() < 2/3);
    }
    

提交回复
热议问题