美文网首页
CocosCreator中,按权重取值

CocosCreator中,按权重取值

作者: 全新的饭 | 来源:发表于2022-11-18 16:11 被阅读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;
    }

相关文章

网友评论

      本文标题:CocosCreator中,按权重取值

      本文链接:https://www.haomeiwen.com/subject/gzypxdtx.html