Write a Function for r and 5()

Write a function for r and 5() that returns a random int between 0 and 5, implement r and 7 ()

💡Strategies for Solving This Problem

Rejection Sampling

Classic random number generation problem. Got this at Google. It's about using one random source to create another with different properties.

The Problem

Given rand5() which returns random int 0-4 uniformly, implement rand7() which returns random int 0-6 uniformly.

Why It's Tricky

Can't just do rand5() + rand5() or rand5() % 7 - these don't give uniform distribution.

Key Insight: Generate Larger Range

Call rand5() twice to get random number 0-24:

result = rand5() * 5 + rand5()

This gives 25 equally-likely outcomes. Since 25 = 3×7 + 4, use first 21 outcomes for rand7(), reject 22-24.

Rejection Sampling

  1. Generate candidate from larger space
  2. If in valid range, return it
  3. Otherwise, try again

Ensures uniform distribution because we only accept equally-likely outcomes.

Expected Calls

Probability of acceptance: 21/25 = 0.84

Expected calls to rand5(): 2 / 0.84 ≈ 2.38

General Pattern

To implement randN() using randM():

  1. Find k such that M^k >= N
  2. Generate number 0 to M^k - 1
  3. Take largest multiple of N that fits
  4. Reject and retry if outside
Scroll to Top