From 7ca8256b777f4085df7ce98f7d6f3d5581a2a132 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Fri, 17 Jan 2020 01:33:31 +0100 Subject: [PATCH] added a weight-based list randomness function --- MLEM/Extensions/RandomExtensions.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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