← 中文资源

简体中文版本

按累计权重随机抽取

只掷一次随机数,沿累计权重逐项累加,落在哪一段就选中哪一项;抽样一万次验证各选项占比逼近权重配比,适合灰度分流、抽奖与按权重的负载分配。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

底层就是函数 pickWeighted。 核心工作在嵌套循环里完成:外层 for (const entry of entries),内层 for (let i = 0; i < draws; i++)。这不是输入检查:RangeError 在耗尽路径上,循环跑完才会执行。

使用要点

  • 守卫 entries.length === 0 满足时靠提前的 throw 短路流程。

常见问题

循环什么时候会停?

当所有尝试耗尽时——throw 位于循环之后,只有最后一次尝试未能提前退出才会发生。

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 pickWeighted。

核心语句

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');

代码示例

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) + '%');
}