我收到一个未知大小的List<Fruit>,通常在4-10件之间:
{ Apples, Orange, Pear, ?, ?, ... } 怎样才能使List的权重达到Apples被选中的最高概率,然后是Orange,然后是Pear?
其效果在本质上应该与从List中选择如下所示的随机项相同:
{ Apples, Apples, Apples, Apples, Orange, Orange, Pear }如果List是固定大小的,我就会
< 0.4,返回Apples。否则,如果< 0.75返回Orange等。请注意,这个问题不是关于selecting a random item from a weighted list的,而是关于对任意长度的现有List进行加权的问题,因为随机选择将导致项目被选择的概率与其在List中的位置成正比。
发布于 2018-12-03 00:58:09
var weightedItems = myList
.Select((item, index)
=> new { Item = item, Weight = 1f / Math.Pow(2, index) });这将给你一个IEnumerable的元组的Item和一个Weight变得越来越小,随着Item的index增加。
Item = Apples, Weight = 1
Item = Orange, Weight = 0.5
Item = Pear , Weight = 0.25等。
显然,您可以根据自己的喜好调整1f / Math.Pow(2, index)部件(计算权重)。我所使用的产品有一个很好的副作用,那就是产生1 >= n > 0,这是一个可预测的范围,并且使每一项被选中的可能性是前一项的一半。
根据您的需求从此结构中选择一个随机项可以如下所示:
Weight迭代Weight >= your random numberhttps://stackoverflow.com/questions/53585982
复制相似问题