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

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

    Here is a working Python implementation of Adam's answer.

    import random
    
    def rand5():
        return random.randint(1, 5)
    
    def rand7():
        while True:
            r = 5 * (rand5() - 1) + rand5()
            #r is now uniformly random between 1 and 25
            if (r <= 21):
                break
        #result is now uniformly random between 1 and 7
        return r % 7 + 1
    

    I like to throw algorithms I'm looking at into Python so I can play around with them, thought I'd post it here in the hopes that it is useful to someone out there, not that it took long to throw together.

提交回复
热议问题