470. Implement Rand10() Using Rand7()
Problem
Using only the given API rand7(), which returns a uniform random integer from 1 to 7, implement rand10(), which returns a uniform random integer from 1 to 10.
Example: many calls to rand10() → each of 1…10 about 10% of the time
Constraints: follow-up: minimise the expected number of rand7() calls.
(rand7() − 1) · 7 + rand7() is uniform on 1..49. Accept values ≤ 40 (a multiple of 10) and return (v − 1) % 10 + 1; otherwise retry. Expected ~2.45 calls to rand7 per rand10.
Complexity: O(1) expected.
class Solution:
def rand10(self) -> int:
while True:
v = (rand7() - 1) * 7 + rand7() # rand7 provided by LeetCode
if v <= 40:
return (v - 1) % 10 + 1
random.seed(7)
def rand7(): return random.randint(1, 7)
cnt = Counter(Solution().rand10() for _ in range(20000))
assert set(cnt) == set(range(1, 11)) and all(1800 < c < 2200 for c in cnt.values())
class SolBase { // provided by LeetCode
private final Random rnd = new Random(7);
int rand7() { return rnd.nextInt(7) + 1; }
}
class Solution extends SolBase {
public int rand10() {
while (true) {
int v = (rand7() - 1) * 7 + rand7();
if (v <= 40) return (v - 1) % 10 + 1;
}
}
}
var rng = rand.New(rand.NewSource(7)) // provided by LeetCode (a seeded stand-in)
func rand7() int { // provided by LeetCode
return rng.Intn(7) + 1
}
func rand10() int {
for {
v := (rand7()-1)*7 + rand7() // uniform on 1..49
if v <= 40 { // rejection sampling keeps 1..40, four of each final value
return (v-1)%10 + 1
}
}
}