Formula for a random dice roll?
Math.floor(Math.random() * 6) + 1 gives integers 1-6 with equal probability.
Generate random numbers with custom range and count
Pseudo-random: deterministic but statistically well-distributed. Fine for games and simulations. For security, use crypto.getRandomValues() instead.
Math.floor(Math.random() * 6) + 1 gives integers 1-6 with equal probability.
Use a Fisher-Yates shuffle on an array [1..45] and pick the first 6 elements. Each combination has an equal probability.
Your computer can't flip a fair coin -- it needs to start somewhere. Most random number generators are pseudo-random: they take a starting "seed" value and run a deterministic algorithm to produce a sequence that looks random. Math.random() in JavaScript is pseudo-random. True random numbers require physical randomness: atmospheric noise, radioactive decay, or thermal noise. For most applications (games, simulations, sampling), pseudo-random is perfectly adequate. For cryptographic use cases, the distinction matters enormously.
If an attacker can figure out the seed used by Math.random(), they can reproduce every "random" value you've generated -- including tokens, session IDs, and password reset links. Browsers now expose the Web Crypto API: crypto.getRandomValues() pulls entropy from the operating system's randomness pool, making it suitable for security-sensitive applications. Whenever you're generating anything that needs to be unguessable, use the crypto API, not Math.random().
The naive approach to picking N random items without repeats -- generate a number, check if it's already been picked, repeat -- gets exponentially slower as you approach the limit. The Fisher-Yates shuffle runs in O(n): go through the array from the last element backwards, at each step swap the current element with a randomly chosen element from the remaining unprocessed portion. The result is a perfect random permutation. This is how modern card shuffling algorithms work.
A good random number generator produces a uniform distribution -- every value in the range is equally likely to appear. Math.random() in range [min, max] is achieved with Math.floor(Math.random() * (max - min + 1)) + min. Watch out for the common mistake: Math.random() * (max - min) + min gives floats, not integers, and can produce max-exclusive results. When your simulation requires other distributions -- Gaussian for natural variation, Poisson for event rates -- you need additional transformations.
The "house edge" in casino games isn't from cheating the random numbers -- it's mathematical design. A roulette wheel has 37 slots (0-36), but European rules let the house take all bets when 0 comes up, creating a 2.7% edge regardless of how perfect the randomness is. Online gambling requires certified random number generators audited by third parties. Provably fair gambling uses cryptographic commitments to let players verify the randomness after each game.