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

前端 未结 30 2839
一个人的身影
一个人的身影 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:15

    There are elegant algorithms cited above, but here's one way to approach it, although it might be roundabout. I am assuming values generated from 0.

    R2 = random number generator giving values less than 2 (sample space = {0, 1})
    R8 = random number generator giving values less than 8 (sample space = {0, 1, 2, 3, 4, 5, 6, 7})

    In order to generate R8 from R2, you will run R2 thrice, and use the combined result of all 3 runs as a binary number with 3 digits. Here are the range of values when R2 is ran thrice:

    0 0 0 --> 0
    .
    .
    1 1 1 --> 7

    Now to generate R7 from R8, we simply run R7 again if it returns 7:

    int R7() {
      do {
        x = R8();
      } while (x > 6)
      return x;
    }
    

    The roundabout solution is to generate R2 from R5 (just like we generated R7 from R8), then R8 from R2 and then R7 from R8.

提交回复
热议问题