我在.NET项目中有一个要求,我需要从集合中选择一个项目,每个项目都分配有权重(从1到10的整数)。
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.
快速复制/
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)]; } }推荐答案
一种不需要将项目多次添加到列表的算法。它也可以使用非整数权重,尽管如果您使用System.Random中的NextDouble,则必须缩放所有权重以将其总和增加1,或者将NextDouble的值乘以S才能得到
Here's an algorithm which doesn't require adding the items multiple times to a list. It can also work with non-integer weights, although if you're using NextDouble from System.Random, you'll have to scale all of the weights to add up to 1, or multiply the value from NextDouble with S to get it in the desired range.
给出一个项目L的列表(I,W),其中I是项目,W是权重:
Given a list L of items (I,W), where I is the item and W is the weight:
更多推荐
我需要带有权重选项的随机算法
发布评论