1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-12-24 17:29:23 +01:00

Added float version of GetRandomWeightedEntry

This commit is contained in:
Ell 2022-02-23 14:35:35 +01:00
parent c360c90f28
commit af7c341d83
2 changed files with 14 additions and 0 deletions

View file

@ -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**

View file

@ -41,5 +41,18 @@ namespace MLEM.Extensions {
throw new IndexOutOfRangeException();
}
/// <inheritdoc cref="GetRandomWeightedEntry{T}(System.Random,System.Collections.Generic.IList{T},System.Func{T,int})"/>
public static T GetRandomWeightedEntry<T>(this Random random, IList<T> entries, Func<T, float> 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();
}
}
}