c# - 基于百分比加权的选择

标签 c# python algorithm random

我有一组值,以及每个值的相关百分比:

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/

相关文章:

c++ - 从备用键值输入创建映射

c# - 在 C# 中处理 DBNull

python - 如何将 eps 文件转换为 png 文件并保持名称?

c# - 有没有办法确定我在 foreach 循环中的哪一行?

python - 如何在 Django 中执行连接和聚合计数

python - 将调整大小的图像上传到 Imgur 而不保存在磁盘上

c - 具有大序列的程序错误 (C)

.net - 最小化网络图中的交叉线

c# - 错误 95 'System.Array' 不包含 'FindIndex' 的定义

c# - 更新查询从 .net 代码返回 0 行。从 SQL Developer 返回 1 行