Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Deriving Random10() function from Random7() in JavaScript
Suppose we have a random7() function that generates random numbers from 1 to 7. We need to create a random10() function that generates random numbers from 1 to 10, using only the random7() function.
Problem
const random7 = () => Math.ceil(Math.random() * 7);
This function yields a random number between 1 and 7 (inclusive) every time we call it. We need to write a random10() function that returns random numbers between 1 and 10 (inclusive) using only this random7() function.
Using Rejection Sampling (Optimal Solution)
The most efficient approach uses rejection sampling. We generate numbers in a range that's evenly divisible by 10, then map the results.
const random7 = () => Math.ceil(Math.random() * 7);
const random10 = () => {
let result;
do {
// Generate a number from 1-49 (7×7 grid)
result = (random7() - 1) * 7 + (random7() - 1);
} while (result >= 40); // Reject 40-48 to keep uniform distribution
return (result % 10) + 1; // Map 0-39 to 1-10
};
// Test the function
for (let i = 0; i
3
7
1
9
4
How It Works
The algorithm works by:
- Creating a 7×7 grid (49 possible outcomes) using two
random7()calls - Rejecting results 40-48 to maintain uniform distribution
- Mapping the remaining 40 outcomes (0-39) to 1-10 using modulo
Alternative: Summation Approach (Less Optimal)
Here's a corrected version of the summation approach, though it's less mathematically sound:
const random7 = () => Math.ceil(Math.random() * 7);
const random10Summation = () => {
let sum = 0; // Initialize sum to 0
for (let i = 0; i
8
3
6
2
9
Comparison
| Method | Uniformity | Efficiency | Calls to random7() |
|---|---|---|---|
| Rejection Sampling | Perfect | High | ~2.45 average |
| Summation | Poor | Fixed | Fixed (10) |
Conclusion
The rejection sampling method provides perfectly uniform distribution and is the optimal solution. The summation approach, while simpler, doesn't guarantee uniform randomness across all outcomes.
