Public Sub Main()
Dim random As New Random()
Dim items() As String = {"物品1", "物品2", "物品3", "物品4", "物品5", "物品6", "物品7", "物品8", "物品9", "物品10"}
Dim probabilities() As Double = {0.9, 0.7, 0.5, 0.3, 0.2, 0.15, 0.12, 0.1, 0.08, 0.05}
' 确保概率之和为1
Dim totalProbability As Double = probabilities.Sum()
For i As Integer = 0 To probabilities.Length - 1
probabilities(i) /= totalProbability
Next
' 随机选择物品1000次并输出
For i As Integer = 1 To 1000
Dim randValue As Double = random.NextDouble()
Dim cumulativeProbability As Double = 0
For j As Integer = 0 To probabilities.Length - 1
cumulativeProbability += probabilities(j)
If randValue <= cumulativeProbability Then
Console.WriteLine("第" & i & "次选中的物品是: " & items(j))
Exit For
End If
Next
Next
End Sub
这段代码将执行以下步骤:
- 初始化一个
Random
对象用于生成随机数。 - 定义物品数组
items
和对应的概率数组probabilities
。 - 确保概率之和为1,通过将每个概率除以总概率来标准化。
- 循环1000次,每次生成一个0到1之间的随机数。
- 根据随机数和累积概率选择物品,并输出每次被选中的物品。