Hello,
I have a requirement in my .net project where I need to select an item from a collection, each item has a Weight (integer from 1 to 10) assigned to it. I need a random generator that would take this weight into consideration i.e. the higher the weight, the more chances the object would be selected. Any code samples in .net are appreciated, although algorithm description is nice, too. Thanks
Edit: Quick copy/paste C# code in case someone stumbles upon this.
class RandomWeightedSelector<T>
{
private List<T> items = new List<T>();
public void Add(T item, uint weight = 1)
{
for (int i = 0; i < weight; i++)
items.Add(item);
}
public T GetRandom()
{
return items[new Random().Next(0, items.Count)];
}
}