You are given a function rand01() that returns 0 or 1 with equal probability. Implement a function rand7() (or rand0to6()) that returns an integer from 0 to 6, each with equal probability (i.e., uniformly at random).
You may call rand01() as many times as you like, but you may not use any other randomness source.
Input: (calls to rand0to6())Output: 0(with probability 1/7)Explanation: Each call to rand0to6() should return0,1,2,3,4,5, or 6with equal probability. This is one possible output.
Input: (calls to rand0to6())Output: 4(with probability 1/7)Explanation: Each call to rand0to6() should return0,1,2,3,4,5, or 6with equal probability. This is one possible output.
The idea is to use multiple calls to rand01() to generate a number in a larger range that covers at least 0 to 6. For example, three calls to rand01() can generate numbers from 0 to 7 (since 2^3 = 8). If the result is 7, we reject and repeat. This ensures each of 0 to 6 is equally likely.
classSolution {
public:// Assume rand01() is provided and returns 0 or 1 uniformly at random
int rand0to6() {
int ans;
while (true) {
ans =4* rand01() +2* rand01() + rand01();
if (ans <7) return ans;
}
}
};
1
2
3
4
5
6
7
8
9
// Assume rand01() is provided and returns 0 or 1 uniformly at randomfuncrand0to6() int {
for {
ans:=4*rand01() +2*rand01() +rand01()
ifans < 7 {
returnans }
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
// Assume rand01() is provided and returns 0 or 1 uniformly at randompublicintrand0to6() {
int ans;
while (true) {
ans = 4 * rand01() + 2 * rand01() + rand01();
if (ans < 7) return ans;
}
}
}
1
2
3
4
5
6
7
8
9
classSolution {
// Assume rand01() is provided and returns 0 or 1 uniformly at random
funrand0to6(): Int {
while (true) {
val ans = 4 * rand01() + 2 * rand01() + rand01()
if (ans < 7) return ans
}
}
}
1
2
3
4
5
6
7
classSolution:
# Assume rand01() is provided and returns 0 or 1 uniformly at randomdefrand0to6(self) -> int:
whileTrue:
ans =4* rand01() +2* rand01() + rand01()
if ans <7:
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
// Assume rand01() is provided and returns 0 or 1 uniformly at random
pubfnrand0to6() -> i32 {
loop {
let ans =4* rand01() +2* rand01() + rand01();
if ans <7 {
return ans;
}
}
}
}
1
2
3
4
5
6
7
8
9
classSolution {
// Assume rand01() is provided and returns 0 or 1 uniformly at random
rand0to6():number {
while (true) {
constans=4*rand01() +2*rand01() +rand01();
if (ans<7) returnans;
}
}
}