Generate Uniform rand3 from rand10
Problem statement
A source function rand10() returns each integer from 0 through 9 with equal probability. Implement a sampler that returns each of 0, 1, and 2 with equal probability.
For this executable practice, the array draws records successive values returned by independent calls to rand10(). Consume values from left to right until your sampler produces one result, then return that result. Ignore all later values. The array always contains a value from 0 through 8, so a result is available.
Your algorithm must preserve a uniform output when the underlying draws are independent and uniform. A direct rand10() % 3 is biased because ten values do not divide evenly into three groups.
Function
rand3FromRand10(draws: int[]) → intExamples
Example 1
draws = [0]return = 0The first draw is accepted and maps to output 0.
Example 2
draws = [9,8]return = 2Reject 9. The next draw is 8, which maps to output 2.
Example 3
draws = [9,9,3,2]return = 0Reject both leading nines. Draw 3 maps to 0; the later 2 is unused.
Constraints
1 <= draws.length <= 100.0 <= draws[i] <= 9.- At least one element of
drawsis less than9. - The recorded sequence is a deterministic testing adapter for one sampler call. In the probabilistic model, each underlying
rand10()call is independent and uniform.