FastPrepGenerate Uniform rand3 from rand10

Generate Uniform rand3 from rand10

NVIDIA logoNVIDIA● MediumNEW GRADOA
Learn

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[]) → int

Examples

Example 1

draws = [0]return = 0

The first draw is accepted and maps to output 0.

Example 2

draws = [9,8]return = 2

Reject 9. The next draw is 8, which maps to output 2.

Example 3

draws = [9,9,3,2]return = 0

Reject 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 draws is less than 9.
  • The recorded sequence is a deterministic testing adapter for one sampler call. In the probabilistic model, each underlying rand10() call is independent and uniform.

More NVIDIA problems

See NVIDIA hiring insights
public int rand3FromRand10(int[] draws) {
    // Write your code here.
}
draws[0]
expected0
Checking account…