An interview question: About Probability

前端 未结 10 1477
清酒与你
清酒与你 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:51

    The problem with your algorithm is that it repeats itself with high probability. My code:

    function g(x) = {
        var s = f(x) + f(x) + f(x); 
        // s = 0, probability:  1/64
        // s = 1, probability:  9/64
        // s = 2, probability: 27/64
        // s = 3, probability: 27/64
        if (s == 2) return 0;
        if (s == 3) return 1;
    
        return g(x); // probability to go into recursion = 10/64, with only 1 additional f(x) calculation
    }
    

    I've measured average number of times f(x) was calculated for your algorithm and for mine. For yours f(x) was calculated around 5.3 times per one g(x) calculation. With my algorithm this number reduced to around 3.5. The same is true for other answers so far since they are actually the same algorithm as you said.

    P.S.: your definition doesn't mention 'random' at the moment, but probably it is assumed. See my other answer.

提交回复
热议问题