尾牙抽獎程式

2022-04-25
作家
Will_Lin
活動攝影
Will_Lin

題目一、

            ///六萬筆員工資料
            string[] employee = new string[60000];
            ///抽獎獎項與數量
            List reward = new List() {
                new KeyValuePair("頭獎-現金1000000",1),
                new KeyValuePair("二獎-現金100000",100),
                new KeyValuePair("三獎-現金50000",200),
                new KeyValuePair("四獎-現金10000",1000),
                new KeyValuePair("五獎-現金5000",20000),
                new KeyValuePair("六獎-現金1000",30000)
            };
            ///這邊模擬假員工6萬筆
            for (int i = 0; i < 60000; i++)
            {
                employee[i] = i.ToString();
            }           

            Random random = new Random();
            ///這邊開始做演算  隨機打亂員工順序
            for (int i = 0; i < 30000; i++)
            { 

                ///這邊採用亂數  但也可以做單純的交叉互換,就看隨機的程度如何  氣泡排序法的概念
                int randomIndex = random.Next(30000, employee.Length - 1);
                string tmp = employee[i];
                employee[i] = employee[randomIndex];
                employee[randomIndex] = tmp; 
            }

            int _EIndex = 0;
            int _LastCount = 0;
            ///接下來我們要開始抽獎囉
            for (int i = reward.Count() -1 ; i >= 0; i--)
            {
                _LastCount = reward[i].Value; 
                while (_LastCount > 0)
                { 
                    Console.WriteLine("恭喜 員工 :" + employee[_EIndex] + " 獲得 :" + reward[i].Key);
                    _LastCount--;
                    _EIndex++;
                }

            } 

 

補充說明

直覺思考會在抽獎的步驟做亂數取員工的動作,但有一個盲點是當員工被抽的數量越來越多後,重複取到已抽過的亂數機率會變大,而導致Timeout情況發生

可以選擇亂序的產生,有序的取,也可以選擇有序的產生,再亂數的取。需要注意的是在亂數這邊當已使用過的樣本數變大,該怎麼去對時間複雜度做收斂