Skip to content

Instantly share code, notes, and snippets.

@songzheng45
Last active September 17, 2018 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save songzheng45/5993d5627a00d75b1885b5bc77bdff0c to your computer and use it in GitHub Desktop.
Save songzheng45/5993d5627a00d75b1885b5bc77bdff0c to your computer and use it in GitHub Desktop.
get lucy prize 随机抽奖品
[Serializable]
public class PrizeDetail:ICloneable
{
    public string Id { get; set; }
    /// <summary>
    /// 奖品名称
    /// </summary>
    public string PrizeName { get; set; }
    /// <summary>
    /// 备注
    /// </summary>
    public string BakNote { get; set; }
    /// <summary>
    /// 奖品金额
    /// </summary>
    public decimal PrizeValue { get; set; }
    /// <summary>
    /// 奖品类别
    /// </summary>
    public string PrizeType { get; set; }
    /// <summary>
    /// 奖品稽核倍数
    /// </summary>
    public int PrizeAuditRate { get; set; }
    /// <summary>
    /// 概率
    /// </summary>
    public double Odds { get; set; }

    /// <summary>
    /// 红包状态 new,opend
    /// </summary>
    public string Status { get; set; }

    public object Clone()
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, this);
        ms.Seek(0, SeekOrigin.Begin);
        return bf.Deserialize(ms);
    }
}

public static PrizeDetail Next(this List<PrizeDetail> list)
{
    long tick = DateTime.Now.Ticks;
    Thread.Sleep(1);
    Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
    var rnum = ran.Next(0, 9999);//将0~100映射到0~10000,提高精度到小数点后2位;生成随机数rnum;
    var randomProbability = (double)rnum / 10000;//再换算为0~100范围
    var target = 0;//命中index
    double min = 0, 
           max = list[0].Odds;
    for (int k = 0; k < list.Count; k++)
    {
        if (randomProbability >= min && randomProbability <= max)//随机出来的中奖概率位于中奖概率区间内
        {
            target = k;
            break;
        }
        min += list[k].Odds;//最小中奖概率
        max += list[k + 1].Odds;//最大中奖概率累计值
    }
    return list[target];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment