相关疑难解决方法(0)

随机加权选择

考虑下面代表经纪人的类:

public class Broker
{
    public string Name = string.Empty;
    public int Weight = 0;

    public Broker(string n, int w)
    {
        this.Name = n;
        this.Weight = w;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想从阵列中随机选择一个Broker,同时考虑它们的权重.

您如何看待下面的代码?

class Program
    {
        private static Random _rnd = new Random();

        public static Broker GetBroker(List<Broker> brokers, int totalWeight)
        {
            // totalWeight is the sum of all brokers' weight

            int randomNumber = _rnd.Next(0, totalWeight);

            Broker selectedBroker = null;
            foreach (Broker broker in brokers)
            {
                if (randomNumber <= broker.Weight)
                {
                    selectedBroker = …
Run Code Online (Sandbox Code Playgroud)

c# random algorithm

54
推荐指数
4
解决办法
3万
查看次数

标签 统计

algorithm ×1

c# ×1

random ×1