CocosCreator中,按权重取值
2022-11-18 本文已影响0人
全新的饭
// 根据权重获取值
// key:可选值;值:权重
private static getValueByWeight<T>(weightMap: Map<T, number>): T {
let targetValue: T = weightMap.keys()[0];
const curRandomValue: number = randomRange(0, 1);
let totalWeight = 0;
for (const v of weightMap.values()) {
totalWeight += v;
}
let curProb = 0;
for (const k of weightMap.keys()) {
curProb += weightMap.get(k) / totalWeight;
if (curProb >= curRandomValue) {
targetValue = k;
break;
}
}
return targetValue;
}