An interview question: About Probability

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

    Here is a solution based on central limit theorem, originally due to a friend of mine:

    /*
    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 1.
    */
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int f() {
      if (rand() % 4 == 0) return 0;
      return 1;
    }
    
    int main() {
      srand(time(0));
      int cc = 0;
      for (int k = 0; k < 1000; k++) { //number of different runs
        int c = 0;
        int limit = 10000; //the bigger the limit, the more we will approach %50 percent
        for (int i=0; i

提交回复
热议问题