C# 红包算法

 
        /// 红包算法
        /// 
        /// 
        /// 
        public static List GetMoneys(RedPacket _redPacket)
        {
            //人均最小金额
            double min = 0.1;
            if (_redPacket.remainMoney < _redPacket.remainCount * min)
                return null;

            int num = _redPacket.remainCount;
            List array = new List();
            Random r = new Random();
            for (int i = 0; i < num; i++)
            {
                if (_redPacket.remainCount == 1)
                {
                    _redPacket.remainCount--;
                    array.Add(Convert.ToDouble(_redPacket.remainMoney.ToString("0.0")));
                    Console.WriteLine(string.Format("第{0}个红包:{1}元", i + 1, Convert.ToDouble(_redPacket.remainMoney.ToString("0.0"))));
                }
                else
                {
                    //(_redPacket.remainMoney - (_redPacket.remainCount - 1) * min):保存剩余金额可以足够的去分配剩余的红包数量
                    double max = (_redPacket.remainMoney - (_redPacket.remainCount - 1) * min) / _redPacket.remainCount * 2;
                    double money = r.NextDouble() * max;
                    money = Convert.ToDouble((money <= min ? min : money).ToString("0.0"));
                    _redPacket.remainCount--;
                    _redPacket.remainMoney -= money;
                    array.Add(money);
                    Console.WriteLine(string.Format("第{0}个红包:{1}元", i + 1, money));
                }
            }
            //再次随机
            return array.OrderBy(o => Guid.NewGuid()).ToList();
        }
    public class RedPacket
    {
        /// 
        /// 剩余的红包数量
        /// 
        public int remainCount { get; set; }

        /// 
        /// 剩余的钱
        /// 
        public double remainMoney { get; set; }
    }


你可能感兴趣的:(红包算法)