jille_Jr icon

[C#] Weighted randomization via tuples

jille_Jr | PRO | 10/09/18 10:57:13 AM UTC | 0 ⭐ | 301 👁️ | Never ⏰ | []
C# |

720 B

|

None

|

0 👍

/

0 👎

/// <summary>Weighted randomization</summary>
/// <example>
/// (string, int)[] weightedColors =
/// {
///     ("red", 500),
///     ("green", 20),
///     ("blue", 300),
///     ("yellow", 666),
/// };
/// string randomColor = WeightedRandomization(weightedColors);
/// </example>
static T WeightedRandomization<T>(IReadOnlyCollection<(T value, int weight)> list, Random random)
{
    if (list == null || list.Count == 0)
        return default(T);
 
    int total = list.Sum(e => e.weight);
    int choice = random.Next(total);
    int sum = 0;
 
    foreach ((T value, int weight) in list)
    {
        sum += weight;
        if (sum >= choice)
            return value;
    }
 
    return list.First().value;
}

Comments