gpt4 book ai didi

C# 加权随机数

转载 作者:行者123 更新时间:2023-11-30 19:53:46 29 4
gpt4 key购买 nike

我需要游戏编程方面的帮助。

您打开一个箱子,并以给定的概率找到一个元素。

元素/几率

一个/10%
B/30%
C/60%

Random random = new Random();
int x = random.Next(1, 101);

if (x < 11) // Numbers 1..10 ( A -> 10% )
{
do_something1(); d
}
else if (x < 41) // Numbers 11..40 ( B -> 30 % )
{
do_something2();
}
else if (x < 101) // Numbers 41..100 ( C -> 60 % )
{
do_something3();
}

就概率而言,这个例子真的有意义吗?您有其他解决方案吗?

提前致谢!

最佳答案

我意识到这有点晚了,但这里有一个没有常量、费力的 if/else 和/或 switch 语句的例子;

public class WeightedChanceParam
{
public Action Func { get; }
public double Ratio { get; }

public WeightedChanceParam(Action func, double ratio)
{
Func = func;
Ratio = ratio;
}
}

public class WeightedChanceExecutor
{
public WeightedChanceParam[] Parameters { get; }
private Random r;

public double RatioSum
{
get { return Parameters.Sum(p => p.Ratio); }
}

public WeightedChanceExecutor(params WeightedChanceParam[] parameters)
{
Parameters = parameters;
r = new Random();
}

public void Execute()
{
double numericValue = r.NextDouble() * RatioSum;

foreach (var parameter in Parameters)
{
numericValue -= parameter.Ratio;

if (!(numericValue <= 0))
continue;

parameter.Func();
return;
}

}
}

使用示例:

WeightedChanceExecutor weightedChanceExecutor = new WeightedChanceExecutor(
new WeightedChanceParam(() =>
{
Console.Out.WriteLine("A");
}, 25), //25% chance (since 25 + 25 + 50 = 100)
new WeightedChanceParam(() =>
{
Console.Out.WriteLine("B");
}, 50), //50% chance
new WeightedChanceParam(() =>
{
Console.Out.WriteLine("C");
}, 25) //25% chance
);

//25% chance of writing "A", 25% chance of writing "C", 50% chance of writing "B"
weightedChanceExecutor.Execute();

关于C# 加权随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46563490/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com