/// Weighted randomization /// /// (string, int)[] weightedColors = /// { /// ("red", 500), /// ("green", 20), /// ("blue", 300), /// ("yellow", 666), /// }; /// string randomColor = WeightedRandomization(weightedColors); /// static T WeightedRandomization(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; }