C# - 根据权重随机取出list中一个元素

//source : 目标列表
//sourceWeight : 目标列表中每个元素对应的权重
void RandomValueByWeight(List<T> source,List<int> sourceWeight)
{
    if(source == null || source.Count <=0)
    {
        return null;
    }
    var weight = 0;
    foreach (var item in sourceWeight) 
    {
        weight += item;
   	}
    
    var random = new System.Random(0,weight - 1);
    var rValue = random.Next(1,)
    var w = 0;
    for (int i = 0; i < length; i++) {
	    w += sourceWeight[i];
        if(w > rValue)
        {
            return source[i];
        }
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/smile_otl/article/details/133877074
今日推荐