我正在尝试为我的随机数生成器添加概率。
这是随机数生成器代码。
'Generate 3 random numbers'
Dim rn As New Random
Dim result1, result2, result3 As Integer
result1 = rn.Next(1, 12)
result2 = rn.Next(1, 12)
result3 = rn.Next(1, 12)
因此这段代码将生成 3 个随机数并将它们保存到单独的变量中。 我希望发生以下情况。
1 has a 20% chance of being selected
2 has a 28% chance of being selected
值必须在 1 到 12 之间,我需要选择 3 个数字 沿着这条线的东西。
我找到了this but it seems to be a little off topic?
这可以用于我想要的吗?
最佳答案
创建一个包含 100 个项目的数组。将值 1
放入数组中的 20 个位置,将值 2
放入数组中的 28 个位置,依此类推。然后选择一个随机数组索引。根据您的值和概率,您可以简化或调整数组的大小。
或者,您可以只存储边界对({1, 20},{2, 48},...),获取小于最高边界值的随机数,然后找到您的边界对的最小对的数字边界值大于或等于随机结果。这是一个例子:
Private rnd As New Random()
Public Function GetValue() As Integer
'max value is 100
Dim boundaries = {
{20, 48, 56, 60, 69, 74, 77, 82, 84, 88, 92, 100},
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
}
Dim r As Integer = rnd.Next(1, 101) 'upper range is exclusive
For i As Integer = 0 To boundaries.GetUpperBound(1)
If boundaries(0, i) >= r Then Return boundaries(1, i)
Next
Throw New Exception() 'code should not be able to get here
End Function
Dim result1 As Integer = GetValue()
Dim result2 As Integer = GetValue()
Dim result3 As Integer = GetValue()
关于vb.net - 如何向随机数生成器添加概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813177/