我有一组值,以及每个值的相关百分比:
a:70% 的机会
b: 20% 几率
c: 10% 的机会
我想根据给定的百分比机会选择一个值(a、b、c)。
我该如何处理?
到目前为止,我的尝试如下所示:
r = random.random()
if r <= .7:
return a
elif r <= .9:
return b
else:
return c
我一直在想出一种算法来处理这个问题。我应该如何处理这个问题,以便它可以处理更大的值集,而不仅仅是将 if-else 流链接在一起。
(伪代码中的任何解释或答案都可以。python 或 C# 实现会特别有帮助)
最佳答案
这是一个完整的 C# 解决方案:
public class ProportionValue<T>
{
public double Proportion { get; set; }
public T Value { get; set; }
}
public static class ProportionValue
{
public static ProportionValue<T> Create<T>(double proportion, T value)
{
return new ProportionValue<T> { Proportion = proportion, Value = value };
}
static Random random = new Random();
public static T ChooseByRandom<T>(
this IEnumerable<ProportionValue<T>> collection)
{
var rnd = random.NextDouble();
foreach (var item in collection)
{
if (rnd < item.Proportion)
return item.Value;
rnd -= item.Proportion;
}
throw new InvalidOperationException(
"The proportions in the collection do not add up to 1.");
}
}
用法:
var list = new[] {
ProportionValue.Create(0.7, "a"),
ProportionValue.Create(0.2, "b"),
ProportionValue.Create(0.1, "c")
};
// Outputs "a" with probability 0.7, etc.
Console.WriteLine(list.ChooseByRandom());
关于c# - 基于百分比加权的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655430/