An interview question: About Probability

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

    As already mentioned your definition is not that good regarding probability. Usually it means that not only probability is good but distribution also. Otherwise you can simply write g(x) which will return 1,0,1,0,1,0,1,0 - it will return them 50/50, but numbers won't be random.

    Another cheating approach might be:

    var invert = false;
    function g(x) {
        invert = !invert;
        if (invert) return 1-f(x);
        return f(x);
    }
    

    This solution will be better than all others since it calls f(x) only one time. But the results will not be very random.

提交回复
热议问题