Ts/Js 实现抽奖功能--根据物品权重计算

  /**
     * 
     * @param vWeight 权重的数组:例如【1,1,1,1,1】
     * @returns //注意:返回的下标加1(占第几个)
     */
  public static GetPrize(vWeight: number[]): number {
        //计算权重之和  prev 是前一次累加后的数值,currVal 是本次待加的数值
        let weightSum = vWeight.reduce((prev, currVal) => {
            return prev + currVal;
        }, 0);
        let random = Math.ceil(Math.random() * weightSum);
        console.log("random ---->" + random);
        let count = 0;
        for (let i = 0; i < vWeight.length; i++) {
            count += vWeight[i];
            if (random <= count) {
                return i + 1;
            }
        }
    }

 

posted @ 2021-07-26 14:01  程序&#128049;  阅读(245)  评论(0编辑  收藏  举报