February 10, 2022

概率抽奖算法

/// <summary>
/// 抽奖
/// </summary>
/// <param name="probabilities">每个奖项的概率</param>
/// <returns>奖项数组下标</returns>
private int LuckyDraw(List<int> probabilities)
{
    if (probabilities is null or { Count: 0 })
    {
        return -1;
    }

    var totalProbability = probabilities.Sum();
    for (var i = 0; i < probabilities.Count; i++)
    {
        var randomNumber = RandomNumberGenerator.GetInt32(1, totalProbability);
        if (randomNumber <= probabilities[i])
        {
            return i;
        }

        totalProbability -= probabilities[i];
    }

    return -1;
}