Expand a random range from 1–5 to 1–7

前端 未结 30 2840
一个人的身影
一个人的身影 2020-11-22 07:29

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

  1. What is a simple so
30条回答
  •  鱼传尺愫
    2020-11-22 08:13

    There is no (exactly correct) solution which will run in a constant amount of time, since 1/7 is an infinite decimal in base 5. One simple solution would be to use rejection sampling, e.g.:

    
    int i;
    do
    {
      i = 5 * (rand5() - 1) + rand5();  // i is now uniformly random between 1 and 25
    } while(i > 21);
    // i is now uniformly random between 1 and 21
    return i % 7 + 1;  // result is now uniformly random between 1 and 7
    

    This has an expected runtime of 25/21 = 1.19 iterations of the loop, but there is an infinitesimally small probability of looping forever.

提交回复
热议问题