randomIndexByWeight static method

int randomIndexByWeight(
  1. List<double> weights
)

使用累积概率法根据权重获取随机索引 使用示例:

void example() {

List

int selectedIndex = randomIndexByWeight(probabilities);

print('Selected index: $selectedIndex');

}

Implementation

static int randomIndexByWeight(List<double> weights) {
  // 1. 验证权重合计是否为100%
  double sum = weights.fold(0, (prev, weight) => prev + weight);
  if ((sum - 100).abs() > 0.000001) {
    // 使用精度范围比较
    throw Exception('Weights must sum to 100%');
  }

  // 2. 生成0-100之间的随机数
  double random = Random().nextDouble() * 100;

  // 3. 累加概率直到超过随机数
  double accumulatedWeight = 0;
  for (int i = 0; i < weights.length; i++) {
    accumulatedWeight += weights[i];
    if (random <= accumulatedWeight) {
      return i;
    }
  }

  // 处理边界情况
  return weights.length - 1;
}