mysql带权重的随机算法,我需要带有权重选项的随机算法

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.

Quick copy/paste C# code in case someone stumbles upon this.

class RandomWeightedSelector

{

private List items = new List();

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)];

}

}

解决方案

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.

Given a list L of items (I,W), where I is the item and W is the weight:

Add all of the weights together. Call this sum S.

Generate a random number between 0 and S (excluding S, but including 0). Call this value R.

Initialize a variable to 0 to keep track of the running total. We'll call this T.

For each item (I,W) in L:

T=T+W

If T > R, return I.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值