选择基于百分比加权 [英] selection based on percentage weighting
问题描述
我有一组值,并为每个关联的百分比:
I have a set of values, and an associated percentage for each:
一:70%的几率
B:20%的几率
C:10%的几率
a: 70% chance
b: 20% chance
c: 10% chance
我要选择一个值(A,B,C)根据给定的百分比机会。
I want to select a value (a, b, c) based on the percentage chance given.
我怎么处理这个?
我尝试到目前为止是这样的:
my attempt so far looks like this:
r = random.random()
if r <= .7:
return a
elif r <= .9:
return b
else:
return c
我卡想出一个算法来处理这个问题。我应该如何处理这个所以它可以处理更大值的集合,而不只是串联起来的if-else流动。
I'm stuck coming up with an algorithm to handle this. How should I approach this so it can handle larger sets of values without just chaining together if-else flows.
(任何解释或伪code答案都是精品。一个Python或C#实现将是非常有用)
(any explanation or answers in pseudo-code are fine. a python or C# implementation would be especially helpful)
推荐答案
下面是在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());
这篇关于选择基于百分比加权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!