diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7395a81..e204d7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ Additions
Improvements
- Generify GenericFont's string drawing
- Added InputHandler mouse and touch position querying that preserves the game's viewport
+- Added float version of GetRandomWeightedEntry
Fixes
- **Fixed a formatting Code only knowing about the last Token that it is applied in**
diff --git a/MLEM/Extensions/RandomExtensions.cs b/MLEM/Extensions/RandomExtensions.cs
index ae553aa..03b4c8f 100644
--- a/MLEM/Extensions/RandomExtensions.cs
+++ b/MLEM/Extensions/RandomExtensions.cs
@@ -41,5 +41,18 @@ namespace MLEM.Extensions {
throw new IndexOutOfRangeException();
}
+ ///
+ public static T GetRandomWeightedEntry(this Random random, IList entries, Func weightFunc) {
+ var totalWeight = entries.Sum(weightFunc);
+ var goalWeight = random.NextDouble() * totalWeight;
+ var currWeight = 0F;
+ foreach (var entry in entries) {
+ currWeight += weightFunc(entry);
+ if (currWeight >= goalWeight)
+ return entry;
+ }
+ throw new IndexOutOfRangeException();
+ }
+
}
}
\ No newline at end of file