diff --git a/MLEM/Extensions/RandomExtensions.cs b/MLEM/Extensions/RandomExtensions.cs index bc581e3..80be53f 100644 --- a/MLEM/Extensions/RandomExtensions.cs +++ b/MLEM/Extensions/RandomExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; namespace MLEM.Extensions { public static class RandomExtensions { @@ -12,5 +13,17 @@ namespace MLEM.Extensions { return entries[random.Next(entries.Count)]; } + public static T GetRandomWeightedEntry(this Random random, IList entries, Func weightFunc) { + var totalWeight = entries.Sum(weightFunc); + var goalWeight = random.Next(totalWeight); + var currWeight = 0; + foreach (var entry in entries) { + currWeight += weightFunc(entry); + if (currWeight >= goalWeight) + return entry; + } + throw new IndexOutOfRangeException(); + } + } } \ No newline at end of file