470. Implement Rand10() Using Rand7() Medium

@problem@discussion
#Math#Rejection Sampling#Randomized#Probability and Statistics



1/**
2 * [470] Implement Rand10() Using Rand7()
3 *
4 * Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.
5 * Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().
6 *  
7 * Example 1:
8 * Input: n = 1
9 * Output: [2]
10 * Example 2:
11 * Input: n = 2
12 * Output: [2,8]
13 * Example 3:
14 * Input: n = 3
15 * Output: [3,8,10]
16 *  
17 * Constraints:
18 * 
19 * 	1 <= n <= 10^5
20 * 
21 *  
22 * Follow up:
23 * 
24 * 	What is the <a href="https://en.wikipedia.org/wiki/Expected_value" target="_blank">expected value</a> for the number of calls to rand7() function?
25 * 	Could you minimize the number of calls to rand7()?
26 * 
27 */
28pub struct Solution {}
29
30// problem: https://leetcode.com/problems/implement-rand10-using-rand7/
31// discuss: https://leetcode.com/problems/implement-rand10-using-rand7/discuss/?currentPage=1&orderBy=most_votes&query=
32
33// submission codes start here
34
35/** 
36 * The rand7() API is already defined for you.
37 * @return a random integer in the range 1 to 7
38 * fn rand7() -> i32;
39 */
40
41impl Solution {
42    pub fn rand10() -> i32 {
43        
44    }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn test_470() {
55    }
56}
57


Back
© 2025 bowen.ge All Rights Reserved.