1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-12-26 10:19:22 +01:00

added a weight-based list randomness function

This commit is contained in:
Ellpeck 2020-01-17 01:33:31 +01:00
parent 7e6534bfc1
commit 7ca8256b77

View file

@ -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<T>(this Random random, IList<T> entries, Func<T, int> 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();
}
}
}