//红包随机拆分 Random ran = new Random(); List<double> randoms = new List<double>(redPacketsList.Count); for (int i = 0; i < redPacketsInfo.RedPacketQuantity - 1; i++) { int max = (totalAmount - (redPacketsInfo.RedPacketQuantity - i)) * 1; int result = ran.Next(1, max); randoms.Add(result); totalAmount -= result; } randoms.Add(totalAmount);
然后通过设置好系数,以处理数据达到服从正太分布的目的:
//正太分布处理 for (int i = 0; i < redPacketsInfo.RedPacketQuantity; i++) { double a = Math.Sqrt(Math.Abs(2 * Math.Log(randoms[i], Math.E))); double b = Math.Cos(2 * Math.PI * randoms[i]); randoms[i] = a * b * 0.3 + 1; }
经过第二次处理后,得到的数据与原始数据有偏差,那么我们通过等比例方式再次处理,以确保拆分后的红包总额等于红包原始总额:
//生成最终的红包数据 double d = originalTotal / randoms.Sum(); SharedRedPacket sharedRedPacket = new SharedRedPacket(); sharedRedPacket.RobbedRedPackets = new List<RobbedRedPacket>(redPacketsList.Count); for (int i = 0; i < redPacketsInfo.RedPacketQuantity - 1; i++) { sharedRedPacket.RobbedRedPackets.Add(new RobbedRedPacket { Amount = (int)Math.Round(randoms[i] * d, 0) }); } sharedRedPacket.RobbedRedPackets.Add(new RobbedRedPacket { Amount = originalTotal - sharedRedPacket.RobbedRedPackets.Sum(p => p.Amount) });
测试
测试效果图如下:
部分代码如下,
Console.WriteLine("是否分享输入Y分享成功,输入N退出"); string result = Console.ReadLine(); if (result == "Y") { var leftRedPacket = sharedRedPacket.RobbedRedPackets.Where(p => p.UserId <= 0).ToList(); var robbedRedPacket = leftRedPacket[new Random().Next(1, leftRedPacket.Count + 1)]; Console.WriteLine("抢到的到红包金额是:" + robbedRedPacket.Amount); Console.WriteLine("-------------------------------------------------------"); }
总结
以上所述是小编给大家介绍的使用.NET Core实现饿了吗拆红包功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!