Whats the most concise way to pick a random element by weight in c#?

后端 未结 4 2041
慢半拍i
慢半拍i 2021-01-02 03:57

Lets assume:

List which element is:

public class Element(){
   int Weight {get;set;}
}

What I want to a

4条回答
  •  一个人的身影
    2021-01-02 04:33

    If you want a generic version (useful for using with a (singleton) randomize helper, consider whether you need a constant seed or not)

    usage:

    randomizer.GetRandomItem(items, x => x.Weight)
    

    code:

    public T GetRandomItem(IEnumerable itemsEnumerable, Func weightKey)
    {
        var items = itemsEnumerable.ToList();
    
        var totalWeight = items.Sum(x => weightKey(x));
        var randomWeightedIndex = _random.Next(totalWeight);
        var itemWeightedIndex = 0;
        foreach(var item in items)
        {
            itemWeightedIndex += weightKey(item);
            if(randomWeightedIndex < itemWeightedIndex)
                return item;
        }
        throw new ArgumentException("Collection count and weights must be greater than 0");
    }
    

提交回复
热议问题