jille_Jr

[C#] Weighted randomization via tuples

Oct 9th, 2018
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.72 KB | None | 0 0
  1. /// <summary>Weighted randomization</summary>
  2. /// <example>
  3. /// (string, int)[] weightedColors =
  4. /// {
  5. ///     ("red", 500),
  6. ///     ("green", 20),
  7. ///     ("blue", 300),
  8. ///     ("yellow", 666),
  9. /// };
  10. /// string randomColor = WeightedRandomization(weightedColors);
  11. /// </example>
  12. static T WeightedRandomization<T>(IReadOnlyCollection<(T value, int weight)> list, Random random)
  13. {
  14.     if (list == null || list.Count == 0)
  15.         return default(T);
  16.  
  17.     int total = list.Sum(e => e.weight);
  18.     int choice = random.Next(total);
  19.     int sum = 0;
  20.  
  21.     foreach ((T value, int weight) in list)
  22.     {
  23.         sum += weight;
  24.         if (sum >= choice)
  25.             return value;
  26.     }
  27.  
  28.     return list.First().value;
  29. }
Add Comment
Please, Sign In to add comment