Random Number 1 to 7 With Equal Probability
Given a function rand5() which generated random numbers from 0 to 5. Use this function to create rand7(). In deep approach was asked and further discussion was made regarding how to generalize it for creating m
random number generator from n
random number generator. Plz give solution with proper explanation.
Analysis
链接:https://www.nowcoder.com/questionTerminal/a475db9aa74747709e65399c0c7d86d2
来源:牛客网
可推广至更加一般的情况,对于利用可以产生1~N的随机数ranN(),生成1~M的随机数,只需要满足
MAX((randN()-1) * N + (randN()-1)) >= M都可以使用以上述方法类似的方法实现。
令 n = N-1 (randN()-1) * N + (randN()-1) 将以等概率生成N进制数 0 ~nn (换成十进制为 (N-1)*10 + (N-1))。 为了让新生成的随机数等概率, 只取前0 ~ (M*k-1) 个数(M*k-1<nn均可) 余M + 1
求得 randM()随机数
Reference:
[将生成1-5随机数函数转换为1-7随机数函数的实现方法] (https://www.jianshu.com/p/71d816fae2e4\
[已知rand7()可以产生1~7的7个数(均匀概率),利用rand7() 产 生 rand10() 1~10(均匀概率)。](https://www.nowcoder.com/questionTerminal/9d06d8f45dca4e45be41d29c389d8a8d\
[给定能随机生成整数 1 到 5 的函数,写出能随机生成整数 1 到 7 的函数。](https://www.nowcoder.com/questionTerminal/a475db9aa74747709e65399c0c7d86d2\
[CSDN: 随机数生成器 ](https://blog.csdn.net/yiqiangeliyou/article/details/46823595\
Solution
Last updated