You are given a function rand2() that returns 0 or 1 with equal probability. Implement a function rand3() that returns 0, 1, or 2, each with equal probability (i.e., uniformly at random).
You may call rand2() as many times as you like, but you may not use any other randomness source.
Input: (calls to rand3())Output: 0(with probability 1/3)Explanation: Each call to rand3() should return0,1, or 2with equal probability. This is one possible output.
Input: (calls to rand3())Output: 1(with probability 1/3)Explanation: Each call to rand3() should return0,1, or 2with equal probability. This is one possible output.
Input: (calls to rand3())Output: 2(with probability 1/3)Explanation: Each call to rand3() should return0,1, or 2with equal probability. This is one possible output.
The key idea is to use the output of rand2() (which returns 0 or 1 with equal probability) to generate a uniform random number in the range [0, 2]. By combining two calls to rand2(), we can generate numbers in [0, 3]. If the result is 3, we reject and repeat. This ensures each of 0, 1, 2 is equally likely.
For example, if rand2() returns 0 or 1, then two calls can make 00, 01, 10, 11 (i.e., 0, 1, 2, 3). We only want 0, 1, 2, so we reject 3.
classSolution {
public:// Assume rand2() is provided and returns 0 or 1 uniformly at random
int rand3() {
int ans;
while (true) {
ans =2* rand2() + rand2();
if (ans <3) return ans;
}
}
};
1
2
3
4
5
6
7
8
9
// Assume rand2() is provided and returns 0 or 1 uniformly at randomfuncrand3() int {
for {
ans:=2*rand2() +rand2()
ifans < 3 {
returnans }
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
// Assume rand2() is provided and returns 0 or 1 uniformly at randompublicintrand3() {
int ans;
while (true) {
ans = 2 * rand2() + rand2();
if (ans < 3) return ans;
}
}
}
1
2
3
4
5
6
7
8
9
classSolution {
// Assume rand2() is provided and returns 0 or 1 uniformly at random
funrand3(): Int {
while (true) {
val ans = 2 * rand2() + rand2()
if (ans < 3) return ans
}
}
}
1
2
3
4
5
6
7
classSolution:
# Assume rand2() is provided and returns 0 or 1 uniformly at randomdefrand3(self) -> int:
whileTrue:
ans =2* rand2() + rand2()
if ans <3:
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
// Assume rand2() is provided and returns 0 or 1 uniformly at random
pubfnrand3() -> i32 {
loop {
let ans =2* rand2() + rand2();
if ans <3 {
return ans;
}
}
}
}
1
2
3
4
5
6
7
8
9
classSolution {
// Assume rand2() is provided and returns 0 or 1 uniformly at random
rand3():number {
while (true) {
constans=2*rand2() +rand2();
if (ans<3) returnans;
}
}
}