C# 是否有等同于 Python 的东西 random.choices()
does C# have something equivalent to Pythons random.choices()
我正在尝试根据他们的选择做出选择 weight/probability
这是我在 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))
我想在 C# 中做同样的事情,如何做?
C# 是否有任何类似于 random.choices() 的方法我只知道 random.Next()
*这个 python 代码工作正常 randome.choice 接受(序列,权重,k)
序列:值,
权重:一个列表,您可以权衡每个值的可能性,
k:返回列表的长度,
我希望为 C# 做同样的事情,
根据概率选择值
你可以得到random.next(0,100),然后用简单的switch case什么的选择相关项。您的域将是这样的,[0-70、70-85、85-100]。如果您需要完整代码,请告诉我。
Random ran = new Random();
int probability = ran.Next(0, 100);
string s;
if (probability == 0)
s = "Heal";
else if (probability <= 70)
s = "Attack";
else if (probability <= 85)
s = "Amplify";
else if (probability <= 100)
s = "Defense";
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;
}
}
然后就可以像Python版本一样调用了:
string[] choices = { "Attack", "Heal", "Amplify", "Defense" };
int[] weights = { 70, 0, 15, 15 };
Random rnd = new Random();
Console.WriteLine(rnd.Choice(choices, weights));
我正在尝试根据他们的选择做出选择 weight/probability
这是我在 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))
我想在 C# 中做同样的事情,如何做? C# 是否有任何类似于 random.choices() 的方法我只知道 random.Next()
*这个 python 代码工作正常 randome.choice 接受(序列,权重,k) 序列:值, 权重:一个列表,您可以权衡每个值的可能性, k:返回列表的长度,
我希望为 C# 做同样的事情, 根据概率选择值
你可以得到random.next(0,100),然后用简单的switch case什么的选择相关项。您的域将是这样的,[0-70、70-85、85-100]。如果您需要完整代码,请告诉我。
Random ran = new Random();
int probability = ran.Next(0, 100);
string s;
if (probability == 0)
s = "Heal";
else if (probability <= 70)
s = "Attack";
else if (probability <= 85)
s = "Amplify";
else if (probability <= 100)
s = "Defense";
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;
}
}
然后就可以像Python版本一样调用了:
string[] choices = { "Attack", "Heal", "Amplify", "Defense" };
int[] weights = { 70, 0, 15, 15 };
Random rnd = new Random();
Console.WriteLine(rnd.Choice(choices, weights));