C# 做一個指定概率的抽獎程序


        static void Main(string[] args)
        {
            //各物品的概率保存在數組里
            float[] area = new float[4]{
                0.980f,
                0.550f,
                0.230f,
                0.010f
            };

            //單次測試
            //Console.WriteLine(Get(area));

            //批量測試
            int[] result = new int[4]{
                0,
                0,
                0,
                0
            };
            for (int i = 0; i < 1770000; i++)    //為了比對結果方便,這里循環的次數是總概率的1000倍
            {
                int n = Get(area);      //本次抽獎結果
                result[n]++;            //統計抽到的次數
            }
            Console.WriteLine("結果:");
            foreach (int times in result)
            {
                Console.WriteLine(times);
            }
        }

        /// <summary>
        /// 獲取抽獎結果
        /// </summary>
        /// <param name="prob">各物品的抽中概率</param>
        /// <returns>返回抽中的物品所在數組的位置</returns>
        private static int Get(float[] prob)
        {
            int result = 0;
            int n = (int)(prob.Sum() * 1000);           //計算概率總和,放大1000倍
            Random r = rnd;
            float x = (float)r.Next(0, n) / 1000;       //隨機生成0~概率總和的數字

            for (int i = 0; i < prob.Count(); i++)
            {
                float pre = prob.Take(i).Sum();         //區間下界
                float next = prob.Take(i + 1).Sum();    //區間上界
                if (x >= pre && x < next)               //如果在該區間范圍內,就返回結果退出循環
                {
                    result = i;
                    break;
                }
            }
            return result;
        }

        private static Random rnd = new Random();

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM