Implement Rand10() Using Rand7()

medium math rejection sampling randomized

Problem

Given the API rand7() — uniform integers in 1..7 — write rand10() that returns a uniform integer in 1..10. You may call rand7() any number of times, but cannot use any other randomness source.

Inputrand7() returns 5, 3 (then 2, 7 ...)
Outputrand10() returns 9 (then a fresh call returns 2 ...)
idx = (row − 1) × 7 + col gives 1..49; accept idx ≤ 40 and map mod 10.

def rand10():
    while True:
        row = rand7()
        col = rand7()
        idx = (row - 1) * 7 + col   # 1..49
        if idx <= 40:
            return ((idx - 1) % 10) + 1
function rand10() {
  while (true) {
    const row = rand7();
    const col = rand7();
    const idx = (row - 1) * 7 + col;  // 1..49
    if (idx <= 40) return ((idx - 1) % 10) + 1;
  }
}
class Solution extends SolBase {
    public int rand10() {
        while (true) {
            int row = rand7();
            int col = rand7();
            int idx = (row - 1) * 7 + col;
            if (idx <= 40) return ((idx - 1) % 10) + 1;
        }
    }
}
class Solution : public SolBase {
public:
    int rand10() {
        while (true) {
            int row = rand7();
            int col = rand7();
            int idx = (row - 1) * 7 + col;
            if (idx <= 40) return ((idx - 1) % 10) + 1;
        }
    }
};
Time: Expected O(1) (geometric with p = 40/49) Space: O(1)