← Math
Math

Randomness and random number generators

Is the version assignment fair, and can grading rebuild the shuffle?

Separate fair random choices from a reproducible sequence of choices.

Outcome

Find which versions raw % k favours, remove the bias by redrawing, shuffle answer options fairly and reproducibly, and pick the right kind of generator.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Modulo bias
Unequal chances from raw % k when the number of raw values is not a multiple of k.
Rejection sampling
Throwing away raw values at or above the last full multiple of k and drawing again.
Fisher–Yates shuffle
Walking from the last position down, swapping each with a uniformly chosen position at or before it. Every order is equally likely when the successive choices are independent and uniform.
Seeded generator Also PRNG
A generator whose sequence follows from its seed. The small noncryptographic generator here supports replay; cryptographic generators can also be seeded, with secret state.
Cryptographic generator Also CSPRNG
A generator whose outputs cannot be predicted from earlier ones. Required for tokens, keys and anything an attacker could exploit.
xorshift32
A small, fast 32-bit generator built from shifts and exclusive-or, used here so the web app, the mobile apps and the grading backend draw the same bytes.

Why this matters

Surveys assign versions, experiments assign users, load balancers pick backends and services generate tokens. Each step turns raw random bits into a choice. Small mapping mistakes make some choices more likely in a way no single run reveals, and a draw that has to be checked or replayed needs a generator and draw order everyone shares.

This lesson assumes modular arithmetic and expected values from earlier lessons.

Random draws and repeatable protocols

A uniform draw gives every allowed value the same probability. Turning raw generator values into a smaller set of choices is another operation: its fairness depends on how many raw values lead to each choice. Modular arithmetic lets you count those possibilities without relying on one random trial.

A seeded pseudorandom generator produces a deterministic sequence from its initial state. Reproducing an assignment or shuffle therefore requires agreement on the generator, the mapping and the order in which draws are consumed. Fairness arguments here assume independent uniform draws; a repeatable finite generator alone does not establish that assumption or provide the unpredictability needed for security tokens.

01Where modulo bias comes from

Where modulo bias comes from

A survey tool must assign questionnaire versions evenly and let the grading backend rebuild the answer order each respondent saw. Its byte % 6 assignment favors some versions, and the iPhone app’s shuffle disagrees with the backend even when they start from the same seed.

The tool’s version counts could be uneven by chance or because of the mapping. Enumerate every possible byte to separate those explanations. Assume each byte is equally likely, so N = 256 raw values and k = 6 versions. Predict the three lines this program prints.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// One random byte (0-255) turned into one of 6 survey versions with byte % 6.
const ways = Array<number>(6).fill(0);

for (let byte = 0; byte < 256; byte++) ways[byte % 6]!++;

const limit = 256 - (256 % 6); // redraw bytes at or above this

console.log(ways.join(" "));
console.log(limit);
console.log((256 / limit).toFixed(4));
How much more often is version 0 assigned than version 5?

The general rule: N = q × k + r. The first r outcomes get q + 1 raw values and the rest get q. With 32-bit values and a million outcomes the gap is 4,295 against 4,294, small but measurable over many draws.

02Reject and redraw

Reject and redraw

Keep only bytes below 252, the largest multiple of 6 that fits, and draw again otherwise. Each version now has exactly 42 bytes. A draw is kept with chance 252/256, so the expected number of draws per assignment is 256/252 ≈ 1.0159. The cost is worst when k is just above half of N: with 129 outcomes from a byte, almost half of all draws are thrown away.

A quiz draws one of 300 bank questions from a single byte. What is the fair limit?

Math.random cannot be seeded and is not cryptographic. Use crypto.getRandomValues for anything unpredictable, and a small seeded generator such as xorshift32 when a draw must be reproducible.

03Broken shuffles

Broken shuffles

Correct version counts do not guarantee fair answer orders. The tool also walks every answer option and swaps it with any position. With independent uniform choices, for 3 options that is 3 × 3 × 3 = 27 equally likely paths onto 6 orders, and 27 is not a multiple of 6: three orders come up 5 times in 27 and three 4 times. Fisher-Yates walks from the last position down and swaps it only with a position at or before it, giving 3 × 2 = 6 paths, one per order.

Paths per order when shuffling 3 answer options
MethodPathsPer order
Swap each with any position274 or 5
Fisher-Yates from the end61

04Draws are the contract

Draws are the contract

05Seeded or cryptographic

Seeded or cryptographic

The same tool also issues private resume links. Which source should create their random tokens?

06Shuffle the survey

Shuffle the survey

The survey team needs both balanced version assignment and a stable grading replay. Count the mapping’s imbalance, calculate the redraw limit and cost, then restore the agreed shuffle protocol. A loop using the right index range can still replay the wrong order if it consumes a byte that should have been rejected.

A survey’s randomizer

Find the modulo bias, assign versions fairly, then rebuild the answer order.

  1. easy · M-RANDOM-V4-1 Find the modulo bias
  2. medium · M-RANDOM-V4-2 Assign versions fairly
  3. hard · M-RANDOM-V4-3 Rebuild the answer order
In the frontend A fair prize draw in Next.js and Svelte Optional

A prize draw among respondents uses crypto.getRandomValues for an unpredictable 32-bit value and redraws values at or above the last full multiple of the number of entries, so everyone has the same chance.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useState } from "react";

// Every respondent in the prize draw equally likely: 32-bit values above the last full multiple are redrawn.
function pick<T>(entries: T[]): T {
  const limit = 2 ** 32 - (2 ** 32 % entries.length);
  const word = new Uint32Array(1);
  do crypto.getRandomValues(word);
  while (word[0]! >= limit);

  return entries[word[0]! % entries.length]!;
}

export function DrawWinner({ respondents }: { respondents: string[] }) {
  const [winner, setWinner] = useState<string | null>(null);

  if (respondents.length === 0)
    return <p>No respondents have entered the prize draw.</p>;

  return (
    <p>
      <button onClick={() => setWinner(pick(respondents))}>Draw a winner</button>{" "}
      {winner}
    </p>
  );
}

Check this idea later
Assume a load balancer’s hash is uniform over 32-bit values. How large is the imbalance from hash % 3?
Two clients shuffle with the same seed but different libraries’ “uniform integer” functions. Will they agree?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The survey tool is a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.