题目描述
Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.
Do NOT use system’s Math.random().
Example 1:
Input: 1
Output: [7]
Example 2:
Input: 2
Output: [8,4]
Example 3:
Input: 3
Output: [8,1,10]
Note:
rand7 is predefined.
Each testcase has one argument: n, the number of times that rand10 is called.
rand7 返回均匀分布的1到7,要求根据rand7 实现一个rand10, 要求返回均匀分布的1到10。
解决思路是先构建一个randN, N 要求是 10 的整数倍。由randN % 10 可以得到rand10。
由rand7 可以得到 rand49 , rand49 通过过滤掉大于等于40 的可以得到 rand40, 进而可以得到rand10。综上,解决思路如下:
rand7 -> rand49 -> rand40 -> rand10
此解决方案可以推广到所有randN 生成randM (N < M) 的场景。
C++ 实现
1 | // The rand7() API is already defined for you. |