randomIndexByWeight static method
根据权重列表随机返回索引,权重累积法
要求 weights 列表内的权重总和为100(百分比),每个数为 double 类型。
示例:
List<double> probabilities = [10, 15, 5, 20, 10, 5, 15, 5, 10, 5]; // 总和100%
int selectedIndex = CommonUtil.randomIndexByWeight(probabilities);
print('Selected index: $selectedIndex');
返回值: 返回被选中的索引,整数类型。
抛出异常: 当权重总和不为100时抛出异常。
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;
}