C#最简单的抽奖实现
Dictionary<string, int> prizes = new Dictionary<string, int> { { "香蕉", 1 }, { "苹果", 2 }, { "辣椒", 3 }, { "梨", 4 } }; string result =""; while (result != null) { result = Draw(prizes); Console.WriteLine($"恭喜你抽了个:{result??"寂寞"}"); } /// 抽奖算法 static string Draw(Dictionary<string, int> prizes) { int totalWeight = prizes.Values.Sum(); int randomNumber =new Random().Next(totalWeight); int currentWeight = 0; foreach (var prize in prizes) { currentWeight += prize.Value; if (randomNumber < currentWeight) { prizes[prize.Key]--; // 减少剩余数量 return prize.Key; } } return null; // 如果所有奖品都抽完了,返回null }
本文来自博客园,作者:WantRemake,转载请注明原文链接:https://www.cnblogs.com/SmallChen/p/18276295