C# 加权随机数 [英] C# weighted random numbers

查看:86
本文介绍了C# 加权随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help with the programming of a game.

您打开一个箱子,并以给定的概率找到一件物品.

You open a chest and with a given probability you find an item.

物品/机会

A/10%
乙/30%
C/60%

A / 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();
}

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

Does this example really make sense, in terms of probability? Do you have another solution?

先谢谢你!

推荐答案

我同意 @Timothy,我会寻求一个更易于维护的解决方案,您不依赖于 魔数 来分割你的概率.此外,这是个人偏好,但我也称其为比率而不是百分比,否则100"将成为另一个神奇数字,您将自己限制在 1% 的最小概率.通过这种方式,您可以按 1:10:200 或随意拆分:

I agree with @Timothy, I'd go for a more maintainable solution, where you're not relying on magic numbers to split your probabilities. Also, it's personal preference, but I'd also call it ratio rather than percent, otherwise "100" becomes another magic number, and you limit yourself to a minimum probability of 1%. This way you can split it 1:10:200 or however you please:

public static readonly int RATIO_CHANCE_A = 10;
public static readonly int RATIO_CHANCE_B = 30;
//                         ...
public static readonly int RATIO_CHANCE_N = 60;

public static readonly int RATIO_TOTAL = RATIO_CHANCE_A
                                       + RATIO_CHANCE_B
                                         // ...
                                       + RATIO_CHANCE_N;

Random random = new Random();
int x = random.Next(0, RATIO_TOTAL);

if ((x -= RATIO_CHANCE_A) < 0) // Test for A
{ 
     do_something1();
} 
else if ((x -= RATIO_CHANCE_B) < 0) // Test for B
{ 
     do_something2();
}
// ... etc
else // No need for final if statement
{ 
     do_somethingN();
}

编辑:更通用的解决方案

这篇关于C# 加权随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆