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()
.
Input: 1 Output: [7]
Input: 2 Output: [8,4]
Input: 3 Output: [8,1,10]
rand7
is predefined.- Each testcase has one argument:
n
, the number of times thatrand10
is called.
- What is the expected value for the number of calls to
rand7()
function? - Could you minimize the number of calls to
rand7()
?
/**
* The rand7() API is already defined for you.
* @return a random integer in the range 1 to 7
* fn rand7() -> i32;
*/
impl Solution {
pub fn rand10() -> i32 {
let mut a = rand7();
let mut b = rand7() * 7;
while a + b > 47 {
a = rand7();
b = rand7() * 7;
}
(a + b + 2) % 10 + 1
}
}