gpt4 book ai didi

c# - 随机加权选择

转载 作者:IT王子 更新时间:2023-10-29 03:48:31 27 4
gpt4 key购买 nike

考虑下面代表 Broker 的类:

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

public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}

我想从数组中随机选择一个 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 = broker;
break;
}

randomNumber = randomNumber - broker.Weight;
}

return selectedBroker;
}


static void Main(string[] args)
{
List<Broker> brokers = new List<Broker>();
brokers.Add(new Broker("A", 10));
brokers.Add(new Broker("B", 20));
brokers.Add(new Broker("C", 20));
brokers.Add(new Broker("D", 10));

// total the weigth
int totalWeight = 0;
foreach (Broker broker in brokers)
{
totalWeight += broker.Weight;
}

while (true)
{
Dictionary<string, int> result = new Dictionary<string, int>();

Broker selectedBroker = null;

for (int i = 0; i < 1000; i++)
{
selectedBroker = GetBroker(brokers, totalWeight);
if (selectedBroker != null)
{
if (result.ContainsKey(selectedBroker.Name))
{
result[selectedBroker.Name] = result[selectedBroker.Name] + 1;
}
else
{
result.Add(selectedBroker.Name, 1);
}
}
}


Console.WriteLine("A\t\t" + result["A"]);
Console.WriteLine("B\t\t" + result["B"]);
Console.WriteLine("C\t\t" + result["C"]);
Console.WriteLine("D\t\t" + result["D"]);

result.Clear();
Console.WriteLine();
Console.ReadLine();
}
}
}

我不是很自信。当我运行这个时,Broker A 总是比 Broker D 获得更多的命中,并且它们具有相同的权重。

有没有更准确的算法?

谢谢!

最佳答案

您的算法几乎是正确的。但是,测试应该是<而不是 <= :

if (randomNumber < broker.Weight)

这是因为 0 包含在随机数中,而 totalWeight是独家的。换句话说,权重为 0 的经纪人仍然有很小的机会被选中——根本不是你想要的。这说明经纪人 A 的命中率高于经纪人 D。

除此之外,您的算法很好,实际上是解决此问题的规范方法。

关于c# - 随机加权选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com