C# 有什么等同于 Python 的 random.choices()

Viz*_*rer 0 c# python unity-game-engine probability-distribution

我正在尝试根据他们的体重/概率做出选择

这是我在 python 中所拥有的:

import random

myChoiceList = ["Attack", "Heal", "Amplify", "Defense"]
myWeights = [70, 0, 15, 15] // % probability = 100% Ex. Attack has 70% of selection

print(random.choices(myChoicelist , weights = myWeights, k = 1))
Run Code Online (Sandbox Code Playgroud)

我想在 c# 中做同样的事情,如何做到这一点?C# 是否有任何类似于 random.choices() 的方法,我所知道的是 random.Next()

*这个python代码工作正常randome.choice接受(序列,权重,k)序列:值,权重:一个列表,你可以权衡每个值的可能性,k:返回列表的长度,

我希望对 C# 做同样的事情,根据概率选择值

Ano*_*ard 5

C# 没有像这样内置任何东西,但是,添加扩展方法来重新创建相同的基本行为并不难:

static class RandomUtils
{
    public static string Choice(this Random rnd, IEnumerable<string> choices, IEnumerable<int> weights)
    {
        var cumulativeWeight = new List<int>();
        int last = 0;
        foreach (var cur in weights)
        {
            last += cur;
            cumulativeWeight.Add(last);
        }
        int choice = rnd.Next(last);
        int i = 0;
        foreach (var cur in choices)
        {
            if (choice < cumulativeWeight[i])
            {
                return cur;
            }
            i++;
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用类似于 Python 版本的方式调用它:

string[] choices = { "Attack", "Heal", "Amplify", "Defense" };
int[] weights = { 70, 0, 15, 15 };

Random rnd = new Random();
Console.WriteLine(rnd.Choice(choices, weights));
Run Code Online (Sandbox Code Playgroud)