Generate Random numbers without using any external functions

后端 未结 9 983
梦如初夏
梦如初夏 2020-12-08 16:26

This was questions asked in one of the interviews that I recently attended.

As far as I know a random number between two numbers can be generated as follows

9条回答
  •  执念已碎
    2020-12-08 16:40

    Poisson Random Generator

    Lets say we start with an expected value 'v' of the random numbers. Then to say that a sequence of non negative integers satisfies a Poisson Distribution with expected value v means that over subsequences, the mean(average) of the value will appear 'v'. Poisson Distribution is part of statistics and the details can be found on wikipedia. But here the main advantage of using this function are: 1. Only integer values are generated. 2. The mean of those integers will be equal to the value we initially provided.

    It is helpful in applications where fractional values don't make sense. Like number of planes arriving on an airport in 1min is 2.5(doesn't make sense) but it implies that in 2 mins 5 plans arrive.

    int poissonRandom(double expectedValue) {
      int n = 0; //counter of iteration
      double limit; 
      double x;  //pseudo random number
      limit = exp(-expectedValue);
      x = rand() / INT_MAX; 
      while (x > limit) {
        n++;
        x *= rand() / INT_MAX;
      }
      return n;
    }
    

    The line

    rand() / INT_MAX
    

    should generate a random number between 0 and 1. So we can use time of the system. Seconds / 60 will serve the purpose. Which function we should use is totally application dependent.

提交回复
热议问题