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

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

    The premise behind Adam Rosenfield's correct answer is:

    • x = 5^n (in his case: n=2)
    • manipulate n rand5 calls to get a number y within range [1, x]
    • z = ((int)(x / 7)) * 7
    • if y > z, try again. else return y % 7 + 1

    When n equals 2, you have 4 throw-away possibilities: y = {22, 23, 24, 25}. If you use n equals 6, you only have 1 throw-away: y = {15625}.

    5^6 = 15625
    7 * 2232 = 15624

    You call rand5 more times. However, you have a much lower chance of getting a throw-away value (or an infinite loop). If there is a way to get no possible throw-away value for y, I haven't found it yet.

提交回复
热议问题