forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
48 lines (40 loc) · 1.1 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/// Source : https://leetcode.com/problems/implement-rand10-using-rand7/description/
/// Author : liuyubobobo
/// Time : 2018-08-05
#include <iostream>
#include <cassert>
using namespace std;
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
int rand7(){
return rand() % 7 + 1;
}
/// Rejection Sampling improved
/// Utilizing out-of-range-samples
/// The accurate expectation for calling number of rand7() can be seen here:
/// https://leetcode.com/problems/implement-rand10-using-rand7/solution/
///
/// Time Complexity: O(1)
/// Space Complexity: O(1)
class Solution {
public:
int rand10() {
int a = -1, b = rand7(), M = 7;
do{
a = b;
b = rand7();
int randNum = 7 * (a - 1) + b - 1;
int largest = 7 * (M - 1) + 7 - 1;
M = largest % 10 + 1;
if(randNum < largest - largest % 10)
return randNum % 10 + 1;
b = randNum % 10 + 1;
}while(true);
assert(false);
return -1;
}
};
int main() {
return 0;
}