FastPrepGenerate Rand7 from Rand5

Generate Rand7 from Rand5

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

draws contains successive results from a uniform rand5() function, each between 1 and 5. Consume draws in pairs to simulate one uniform rand7() result.

Return a value from 1 through 7 as soon as rejection sampling accepts a pair. Return -1 if the provided stream ends first.

Function

rand7FromRand5Draws(draws: int[]) → int

Examples

Example 1

draws = [5,5,2,3]return = 1

The first pair maps to 24 and is rejected. The second maps to 7, which becomes 1.

Constraints

  • 0 <= draws.length <= 10^5.
  • Every draw is between 1 and 5.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int rand7FromRand5Draws(int[] draws) {
  // Write your code here.
}
draws[5,5,2,3]
expected1
Checking account…