How randomness works in a computer
A computer doesn't generate true randomness: it generates pseudo-random numbers using an algorithm that starts from a "seed" (typically the current time at microsecond precision). If you know the seed and the algorithm, you can predict every future number. Fatal for cryptography; irrelevant for casual raffles.
Modern browsers expose crypto.getRandomValues, which pulls entropy
from the OS (mouse movement, CPU jitter, hardware events) and produces
cryptographically secure numbers. We use it when needed; otherwise
Math.random is enough.
Math.random vs crypto.getRandomValues
- Math.random: fast, lightweight, uniform distribution. Fine for games, casual raffles, animations, simulations.
- crypto.getRandomValues: secure against adversaries. Required for tokens, keys, public unique IDs, passwords. Costlier but still instant at human scale.
No repeats: the Fisher-Yates shuffle problem
Generating 10 unique numbers between 1 and 100 isn't trivial: naive 10 random
draws have a high collision probability. The right solution is to build a
[1..100] array, shuffle it with the Fisher-Yates algorithm, and take
the first 10. That guarantees uniqueness and uniform distribution. It's what we
do when "no repeats" is on.
Practical use cases
- Informal raffles: "pick a number 1 to N, winner is..."
- Random assignment: split a team into groups, decide who presents first.
- Software testing: generate test data, simulate loads, fuzz testing.
- Low-stakes decisions: "do I go to the gym today?" → 1 = yes, 2 = no.
- Education: generate math problems with changing numbers.
- Statistics: sample populations randomly.
When NOT to use this generator
- Legally binding raffles: physical-prize giveaways need certified systems and, in many countries, notary presence.
- Key or password generation: use a dedicated password generator (we also have one).
- Lottery picks "to win": a lottery is an independent physical process; no algorithm predicts or improves your odds.
Uniform distribution: the invisible detail
A good RNG spreads numbers uniformly: 1000 picks between 1 and 10 should give ~100 of each (with normal statistical variance). Bad algorithms bias certain values. Modern ones (xorshift, PCG, those used by V8 or SpiderMonkey) are well tested and don't have this problem in practice.