Random Number Picker Algorithm: Math.random vs CSPRNG

Contents
When you draw event winners or pick prize and lottery numbers, the most important criteria are fairness and unpredictability. Random numbers may appear on screen, but if the implementation is biased or the next value can be predicted, the draw loses all credibility. This post explains why JavaScript's random number generation is a problem, and how to draw fairly with no bias.
Summary
- ①
Math.random()is a predictable pseudo-random number generator (PRNG), so it isn't suitable anywhere fairness matters, such as prize draws or picking winners.- ② Combine a CSPRNG built on
crypto.getRandomValues()with Fisher-Yates shuffle and reservoir sampling, and you can draw fairly with no bias.- ③ If building it yourself is a hassle, you can use the CSPRNG-based fair draw in our free tool right away.
Why your random number method decides the draw
A computer is a deterministic system that runs fixed algorithms. Pure software alone can't produce truly random values, so it calculates values that look random — pseudo-random numbers. How that calculation works is what determines whether your draw is fair.
The limits of Math.random()
Math.random() runs on a pseudo-random number generator (PRNG). JavaScript engines such as V8 use xorshift128+ or an LCG (Linear Congruential Generator) family algorithm internally.
- Seed-based determinism: Once the initial seed and internal state are set, every number that follows is fixed.
- Predictability: Watch a few numbers in a row and you can mathematically reconstruct the previous state or predict the next value.
- Risk of rigging: In a prize draw or winner selection, someone can calculate the pattern and cheat to raise their odds of winning.
The bias a bad shuffle creates
When you shuffle a list or pull K items with no repeats, the common array.sort(() => Math.random() - 0.5) approach seems to work fine on short arrays, but it creates statistical bias.
The number of possible permutations of N elements is N! (N factorial). But the number of internal decision paths a JavaScript sort algorithm (QuickSort, Timsort, and so on) can take when it calls a random comparison function is closer to N^N. In most cases N^N is not an integer multiple of N!, so some permutations come up more often than others — a probabilistic imbalance.
How to draw winners fairly, with no bias
To remove bias, you need three things working together: (1) an unpredictable source of random numbers, (2) a shuffle algorithm that gives every permutation the same probability, and (3) a selection method that stays safe on large data sets. Below are the principles and the code you need to build it yourself.
1) Generate unpredictable random numbers with crypto.getRandomValues()
crypto.getRandomValues() uses a cryptographically secure pseudorandom number generator (CSPRNG).
- Entropy source: It gathers randomness from physical phenomena at the operating system level, such as mouse movement, CPU interrupt timestamps, and keyboard input noise.
- Non-invertibility: Even if someone knows every random number generated in the past, predicting the next value or tracing back the internal seed is effectively impossible.
- Fairness: Use a CSPRNG anywhere reliability matters — cash prizes, winner drawings, or encryption key generation.
When you take a 32-bit integer from crypto.getRandomValues() (0 to 2^32-1) and map it to the range you want, [0, M-1], applying just % M (the modulo operation) creates modulo bias. Unless 2^32 is a multiple of M, the lower numbers come up slightly more often. To eliminate that, compute a limit using rejection sampling.
Rejection Limit = 2^32 − (2^32 mod M)
If the random number R you draw is at or above this limit, throw it away and draw again. That gives you an even probability distribution.
2) Make every permutation equally likely with Fisher-Yates shuffle
The Fisher-Yates shuffle (Durstenfeld variant) starts at the back of the array (N-1). At each step it picks a random index j from the part that isn't fixed yet (0 to i) and swaps the two positions.
- Time complexity: O(N). It walks the array once.
- Space complexity: O(1). It shuffles in place with no extra array.
If you calculate the probability that a particular element lands at position i, you can see why this method is even.
- The probability that a particular element is chosen for the last position (N-1) is 1/N.
- The probability that it is chosen for the second-to-last position (N-2) is (1 − 1/N) × 1/(N-1) = (N-1)/N × 1/(N-1) = 1/N, since it has to survive the first step and then be picked in this one.
- In general, the probability that a particular element is chosen for the k-th position is (N-1)/N × (N-2)/(N-1) × … × (k-1)/k × 1/(k-1) = 1/N.
In other words, every element has exactly the same 1/N chance of landing in any position, and all N! possible permutations come up with equal probability, 1/N! each.
3) Handle large data sets with reservoir sampling
Suppose you need to pick a few numbers with no repeats from a huge range, like 1 to 1,000,000, or you need to draw K items from a data stream where you don't know the total count in advance. Building the whole array in memory and shuffling it is inefficient. Use reservoir sampling instead.
Create a reservoir array of size K, then read the stream one item at a time and process it like this. Below, i is a zero-based index, the same as in the code.
- Fill the first K items (indexes 0 to K-1) into the reservoir unconditionally.
- When the item at index i arrives (where i is K or greater), generate a random integer j between 0 and i.
- If j is less than K, replace the item at reservoir position j with the current input value at index i.
Now suppose the total number of items is N. Let's work out the probability that a particular item is still in the reservoir after the final step. For an item that arrives n-th in the stream (counting from 1, which corresponds to index i = n − 1 in the zero-based code), the probability that it stays in the reservoir all the way to the end is:
P(winning) = K/n × (1 − 1/(n+1)) × (1 − 1/(n+2)) × … × (1 − 1/N) = K/n × n/(n+1) × (n+1)/(n+2) × … × (N-1)/N = K/N
Even without knowing the total size N in advance, you can fairly sample K of N items without replacement in a single pass (O(N)) using only O(K) memory.
Implementation code: CSPRNG + Fisher-Yates + reservoir sampling
The code below is a TypeScript example that includes CSPRNG-based modulo bias removal, Fisher-Yates shuffle, and reservoir sampling.
/**
* Generate a random integer using a CSPRNG (with modulo bias removed)
* @param min Minimum value (inclusive)
* @param max Maximum value (inclusive)
*/
export function getRandomIntSecure(min: number, max: number): number {
if (min > max) {
throw new Error("min must be less than or equal to max.");
}
const range = max - min + 1;
if (range === 1) return min;
const totalValues = 0x100000000; // 2^32
const limit = totalValues - (totalValues % range);
const array = new Uint32Array(1);
let randomValue: number;
do {
crypto.getRandomValues(array);
randomValue = array[0];
} while (randomValue >= limit);
return min + (randomValue % range);
}
/**
* CSPRNG-based Fisher-Yates pick with no repeats (K items)
* @param array Source array of entrants or numbers
* @param k Number of winners to pick (shuffles the whole array if omitted)
*/
export function pickRandomItems<T>(array: T[], k?: number): T[] {
const result = [...array];
const count = k !== undefined ? Math.min(k, result.length) : result.length;
for (let i = result.length - 1; i > result.length - 1 - count; i--) {
const j = getRandomIntSecure(0, i);
[result[i], result[j]] = [result[j], result[i]];
}
return result.slice(result.length - count);
}
/**
* Reservoir sampling for large ranges or streamed data
* @param min Start of the range
* @param max End of the range
* @param k Number of winners to pick
*/
export function reservoirSampleRange(min: number, max: number, k: number): number[] {
const total = max - min + 1;
const sampleCount = Math.min(k, total);
const reservoir: number[] = [];
// 1. Fill the initial reservoir with K items
for (let i = 0; i < sampleCount; i++) {
reservoir.push(min + i);
}
// 2. Decide randomly whether to replace the item at position i
for (let i = sampleCount; i < total; i++) {
const currentValue = min + i;
const j = getRandomIntSecure(0, i);
if (j < sampleCount) {
reservoir[j] = currentValue;
}
}
return reservoir;
}
Check whether your results are fair: chi-square goodness-of-fit test
If you want to confirm that your drawing tool doesn't favor certain numbers or participants, you can use a statistical test. Say you run N total draws across K categories. Let the observed frequency be Oᵢ and the theoretical expected frequency be Eᵢ = N/K. The chi-square statistic χ² is defined as:
χ² = Σ(from i=1 to K) (Oᵢ − Eᵢ)² / Eᵢ
- Null hypothesis (H₀): The assumption that the random selection algorithm follows a uniform probability distribution with no bias.
- Degrees of freedom (df): K − 1
- Decision rule: If the calculated χ² statistic is smaller than the chi-square critical value at the significance level (α = 0.05), the picker is considered statistically unbiased.
Implementing this kind of statistical test yourself and checking it every time is a hassle. The tool below already applies CSPRNG-based modulo bias removal and Fisher-Yates shuffle, so you get unbiased results right away without writing any verification code.
Free · built on cryptographic randomness · fair draws with no repeats

Math.random() vs. crypto.getRandomValues()
| Item | Math.random() | crypto.getRandomValues() |
|---|---|---|
| Generation method | Pseudo-random (PRNG) | Cryptographically secure pseudo-random (CSPRNG) |
| Predictability | The next value can be inferred from previous values | Working backward is practically impossible |
| Seed source | Internal algorithm state | OS-level physical entropy |
| Best suited for | Game effects, simple random visuals | Giveaways and winner draws, encryption key generation |
How to Ensure Fairness in Practice
Transparency in your process matters as much as the algorithm.
- Publish the seed or hash in advance: If you post the SHA-256 hash of the participant list or the seed value on an official board before the draw, anyone can reproduce and verify the same result afterward.
- Record the screen and keep logs: Record everything from entering the list to clicking the draw button to the results screen, and keep the drawn random values and timestamp logs so you can submit them if needed.
- Clean up duplicate data: Before the draw, merge duplicate entries from the same person (phone number, email, account ID) into one.
- Use a client-side tool: To reduce the chance of server-side tampering, it's better to use a client-side drawing tool that runs
crypto.getRandomValues()directly in the browser.
Wrapping Up
For a fair drawing, use a CSPRNG built on crypto.getRandomValues() instead of the predictable Math.random(), and build your permutation with a Fisher-Yates shuffle rather than array.sort(). With large datasets, reservoir sampling lets you draw without the memory burden, and a chi-square test lets you check that the results are uniform. If you'd rather not build it yourself and just want a fair result right away, try the tool below.
Free · built on cryptographic randomness · fair draws with no repeats
Frequently Asked Questions
Q1. Can a winner picked with Math.random() cause legal problems?
For a small internal event or a draw that's just for fun, using Math.random() is unlikely to be a problem. But for high-value cash prizes or official events run by government agencies or companies, it's better to use a CSPRNG-based random algorithm to reduce predictability concerns and accusations of bias.
Q2. Is there a difference in winning odds between drawing first place first and fifth place first?
With a uniform random shuffle like the Fisher-Yates algorithm, every entrant has the same chance of winning regardless of the order you draw in. That said, announcing the lower prizes first works better for building excitement during the event.
Q3. When should I allow repeats (sampling with replacement) versus exclude them (sampling without replacement)?
When a number or person must not be drawn again—like generating lottery numbers or picking giveaway winners—use sampling without replacement (no repeats). When each draw should keep the same odds, like rolling dice, use sampling with replacement (repeats allowed).
This article was adapted from our Korean original. Read the Korean original