Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <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;
- }
Add Comment
Please, Sign In to add comment