首页 > 代码库 > 根据权重/百分比获取概率值

根据权重/百分比获取概率值

public int GetAward()        {            int result = 0;          var timeSpanAwardList = new List<Award>();            var timeList = new List<object>() {};            timeSpanAwardList.ForEach(t =>            {                if (t.DailyQuantity <= 100) //如果每日已发数量>=每日可发数量就排除抽奖列表                {                    timeSpanAwardList.Remove(t);                }            });            //当前可参与抽奖的奖品的设置总数            if (timeSpanAwardList.Count > 0)            {                var countRangeList = new List<List<int>>();                //当前所有奖品总数累加和                var currentAllTotalCount = 0;                //计算奖品范围基数值                foreach (var item in timeSpanAwardList)                {                    countRangeList.Add(new List<int>                    {                        currentAllTotalCount + 1,                        currentAllTotalCount + item.TotalQuantity                    });                    currentAllTotalCount += item.TotalQuantity;                }                //根据百分比重新计算随机基数//这里默认百分比100%                var baseCount = int.Parse(Math.Ceiling(currentAllTotalCount/(100/100.0)).ToString(CultureInfo.InvariantCulture));                //以所有奖品总数累加和为上限,1为下限,随机出一位数                var randomNum = new Random().Next(1, baseCount + 1);                //奖品序号                int? awardIndex = null;                for (var i = 0; i < countRangeList.Count; i++)                {                    //判断随机数是否在某个范围基数内,奖品总数范围值越大,中奖几率越高                    if (countRangeList[i][0] <= randomNum && countRangeList[i][1] >= randomNum)                    {                        //如果在范围内,则为奖品序号赋值                        awardIndex = i;                        break;                    }                }                if (awardIndex.HasValue)                {                    //根据奖品序号取得奖品Id,并获取奖品信息返回                 result= timeSpanAwardList[awardIndex.Value].Id;                }            }            return result;        }

public class Award    {        public int Id { get; set; }    /// <summary>    /// 每日抽中次数    /// </summary>        public int DailyQuantity { get; set; }    /// <summary>    /// 库存    /// </summary>        public int TotalQuantity { get; set; }   }

  

  

根据权重/百分比获取概率值