mirror of
https://github.com/Ellpeck/MLEM.git
synced 2024-11-25 22:18:34 +01:00
added a weight-based list randomness function
This commit is contained in:
parent
7e6534bfc1
commit
7ca8256b77
1 changed files with 13 additions and 0 deletions
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue