An interview question: About Probability

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

    Assuming

    P(f[x] == 0) = 1/4
    P(f[x] == 1) = 3/4
    

    and requiring a function g[x] with the following assumptions

    P(g[x] == 0) = 1/2
    P(g[x] == 1) = 1/2
    

    I believe the following definition of g[x] is sufficient (Mathematica)

    g[x_] := If[f[x] + f[x + 1] == 1, 1, 0]
    

    or, alternatively in C

    int g(int x)
    {
        return f(x) + f(x+1) == 1
               ? 1
               : 0;
    }
    

    This is based on the idea that invocations of {f[x], f[x+1]} would produce the following outcomes

    {
      {0, 0},
      {0, 1},
      {1, 0},
      {1, 1}
    }
    

    Summing each of the outcomes we have

    {
      0,
      1,
      1,
      2
    }
    

    where a sum of 1 represents 1/2 of the possible sum outcomes, with any other sum making up the other 1/2.

    Edit. As bdk says - {0,0} is less likely than {1,1} because

    1/4 * 1/4 < 3/4 * 3/4
    

    However, I am confused myself because given the following definition for f[x] (Mathematica)

    f[x_] := Mod[x, 4] > 0 /. {False -> 0, True -> 1}
    

    or alternatively in C

    int f(int x)
    {
        return (x % 4) > 0
               ? 1
               : 0;
    }
    

    then the results obtained from executing f[x] and g[x] seem to have the expected distribution.

    Table[f[x], {x, 0, 20}]
    {0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0}
    
    Table[g[x], {x, 0, 20}]
    {1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1}
    

提交回复
热议问题