C# 和 "Weighted probability"
C# and "Weighted probability"
我希望从列表中的每个项目都有特定的 "weighting" 的人员列表中挑选 1 个人。假设 Person class 具有必要的构造函数。
public class Person {
public string Name { get; set; }
public float Weighting { get; set; }
}
public List<Person> People = new List<Person>();
People.Add(new Person("Tim", 1.0));
People.Add(new Person("John", 2.0));
People.Add(new Person("Michael", 4.0));
现在,我想从这个列表中随机选择一个人。但是 平均 我想选择迈克尔的频率是蒂姆的 4 倍。我想选择 John 的频率是 Michael 的一半 (2/4)。当然,我想选择 Michael 的频率是 John 的两倍。
这有意义吗?
我已经为 select 人准备了基于百分比的代码。如果我只是将它们的 %chance 乘以本例中提供的权重,它不会起作用吗?
此外,我当前的系统只能使用 高达 100% 的机会,仅此而已。关于如何克服此限制的任何建议?我可能必须根据列表中最大的因素来衡量每一次机会?
public static bool Hit(double pct) {
if (rand == null)
rand = new Random();
return rand.NextDouble() * 100 <= pct;
}
还是我遗漏了什么?
您一开始就没有保留百分比。
我会在 0 到所有 Weighting
值的总和之间创建一个随机数。然后直接遍历list,看看这个值是不是低于当前加上自重。
所以:
float r = YourRandomNumber(People.Sum(p => p.Weighting));
float sum = 0;
foreach (Person p in People)
{
if (r < (sum + p.Weighting))
{
// hit
// save the person somewhere
break;
}
else
{
sum += p.Weighting;
}
}
我希望从列表中的每个项目都有特定的 "weighting" 的人员列表中挑选 1 个人。假设 Person class 具有必要的构造函数。
public class Person {
public string Name { get; set; }
public float Weighting { get; set; }
}
public List<Person> People = new List<Person>();
People.Add(new Person("Tim", 1.0));
People.Add(new Person("John", 2.0));
People.Add(new Person("Michael", 4.0));
现在,我想从这个列表中随机选择一个人。但是 平均 我想选择迈克尔的频率是蒂姆的 4 倍。我想选择 John 的频率是 Michael 的一半 (2/4)。当然,我想选择 Michael 的频率是 John 的两倍。
这有意义吗?
我已经为 select 人准备了基于百分比的代码。如果我只是将它们的 %chance 乘以本例中提供的权重,它不会起作用吗?
此外,我当前的系统只能使用 高达 100% 的机会,仅此而已。关于如何克服此限制的任何建议?我可能必须根据列表中最大的因素来衡量每一次机会?
public static bool Hit(double pct) {
if (rand == null)
rand = new Random();
return rand.NextDouble() * 100 <= pct;
}
还是我遗漏了什么?
您一开始就没有保留百分比。
我会在 0 到所有 Weighting
值的总和之间创建一个随机数。然后直接遍历list,看看这个值是不是低于当前加上自重。
所以:
float r = YourRandomNumber(People.Sum(p => p.Weighting));
float sum = 0;
foreach (Person p in People)
{
if (r < (sum + p.Weighting))
{
// hit
// save the person somewhere
break;
}
else
{
sum += p.Weighting;
}
}