Weighted Random Pick With Cumulative Weights

Roll one random number against cumulative weights so each item wins with probability proportional to its weight, then verify the split over many draws.

TypescriptData Integrity

Code

typescriptsnippet
35 lines
interface Weighted<T> {
  item: T;
  weight: number;
}

// One roll against cumulative weights: each item wins its share
function pickWeighted<T>(entries: readonly Weighted<T>[]): T {
  if (entries.length === 0) throw new RangeError('empty entries');
  const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
  const roll = Math.random() * total;
  let cumulative = 0;
  for (const entry of entries) {
    cumulative += entry.weight;
    if (roll < cumulative) return entry.item;
  }
  throw new RangeError('unreachable while weights are non-negative');
}

const variants = [
  { item: 'control', weight: 50 },
  { item: 'variant-a', weight: 30 },
  { item: 'variant-b', weight: 20 },
] satisfies readonly Weighted<string>[];

// Empirical split over many draws approaches the configured weights
const counts = new Map<string, number>();
const draws = 10000;
for (let i = 0; i < draws; i++) {
  const picked = pickWeighted(variants);
  counts.set(picked, (counts.get(picked) ?? 0) + 1);
}

for (const [variant, count] of counts) {
  console.log(variant, ((count / draws) * 100).toFixed(1) + '%');
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

control 49.7%
variant-b 19.8%
variant-a 30.5%

How it works

Weighted Random Pick With Cumulative Weights keeps everything in the function pickWeighted.

The nesting pairs for (const entry of entries) with for (let i = 0; i < draws; i++) — the inner runs once per outer step. Not an input check: RangeError is thrown on the exhaustion path, after the loop finishes without a successful exit.

Caveats

  • The guard entries.length === 0 short-circuits the flow with an early throw when its condition holds.

Core lines

const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
throw new RangeError('unreachable while weights are non-negative');
if (entries.length === 0) throw new RangeError('empty entries');

Interactive Tools for This Topic

FAQ

When does the loop stop?
When every attempt is spent: the throw sits behind the loop, so it happens only after the last attempt fails to exit early.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `pickWeighted` at load time.