public class GetGiftTest
    {
        //奖品1 0.5%  奖品2 2% 奖品3 2.5% 奖品4 5% 奖品5 30% 奖品60%

        static int[] getTimes = new int[6];

        public static void StartTest()
        {
            //奖品概率数组 合起来需要等于100%
            float[] giftlist = new float[6]{
                0.5f,
                2f,
                2.5f,
                5f,
                30f,
                60f
            };

            ////开始抽奖测试
            for (int i = 0; i < 10000; i++)
            {
                int rightGift = GetGift(giftlist);
                getTimes[rightGift]++;
            }

            for (int i = 0; i < giftlist.Length; i++)
            {
                Console.WriteLine("奖品索引" + i + "抽中次数:" + getTimes[i]);
            }
        }

        /// <summary>
        /// 抽奖方法
        /// </summary>
        /// <param name="giftlist">奖品列表</param>
        /// <returns>哪一个奖品中奖</returns>
        public static int GetGift(float[] giftlist)
        {
            double rnum = GetGiftRandom();
            double range = 0;
            for (int i = 0; i < giftlist.Length; i++)
            {
                if (rnum >= range && rnum < range + giftlist[i])
                {
                    return i;
                }
                else
                {
                    range += giftlist[i];
                    continue;
                }
            }
            return giftlist.Length - 1;  //最后一个物品
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="gailv">输入0.5意思就是0.5%的概率</param>
        /// <returns></returns>
        public static bool GaiLv(double gailv)
        {
            double num = GetGiftRandom();
            if (num <= gailv)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static double GetGiftRandom()
        {
            Random ram = new Random(GetRandomSeed());
            double num = Convert.ToDouble(ram.Next(1, 10001)) / 100;
            return num;
        }

        /// <summary>
        /// 生成牛逼的随机种子
        /// </summary>
        /// <returns></returns>
        public static int GetRandomSeed()
        {
            //字节数组,用于存储
            byte[] bytes = new byte[4];
            //创建加密服务,实现加密随机数生成器
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            //加密数据存入字节数组
            rng.GetBytes(bytes);
            //转成整型数据返回,作为随机数生成种子
            return BitConverter.ToInt32(bytes, 0);
        }
    }
 

转载请注明出处: http://bluesd7.com/蓝影闪电的随笔/ContentId/135/C#-抽奖算法

 

评论数量 (0)

    留下一个评论

    剩余2000个字符。 一共限制在2000个字符内.
    发送评论

    搜索

    关于我

    姓名:余钊

    英文名:Joshua

    现居:武汉

    Email: yuzhao_blue@163.com

    关注:架构, 全栈, SQL, 高性能, 高并发

    日历