An interview question: About Probability

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

    If you call f(x) twice in a row, the following outcomes are possible (assuming that successive calls to f(x) are independent, identically distributed trials):

    00 (probability 1/4 * 1/4)
    01 (probability 1/4 * 3/4)  
    10 (probability 3/4 * 1/4)  
    11 (probability 3/4 * 3/4)
    

    01 and 10 occur with equal probability. So iterate until you get one of those cases, then return 0 or 1 appropriately:

    do
      a=f(x); b=f(x);
    while (a == b);
    
    return a;
    

    It might be tempting to call f(x) only once per iteration and keep track of the two most recent values, but that won't work. Suppose the very first roll is 1, with probability 3/4. You'd loop until the first 0, then return 1 (with probability 3/4).

提交回复
热议问题