1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-06-23 21:30:05 +02:00
MLEM/MLEM/Extensions/RandomExtensions.cs

29 lines
954 B
C#
Raw Normal View History

2019-08-06 14:20:11 +02:00
using System;
using System.Collections.Generic;
using System.Linq;
2019-08-06 14:20:11 +02:00
namespace MLEM.Extensions {
public static class RandomExtensions {
public static T GetRandomEntry<T>(this Random random, params T[] entries) {
return entries[random.Next(entries.Length)];
}
public static T GetRandomEntry<T>(this Random random, IList<T> entries) {
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();
}
2019-08-06 14:20:11 +02:00
}
}