Fork me on GitHub

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
}

  

posted @ 2024-06-30 13:31  WantRemake  阅读(31)  评论(0编辑  收藏  举报