如何在vb.net中随机选择几个具有不同概率的值?

时间:2014-11-25 09:02:05

标签: vb.net random distribution

我试图生成虚拟数据来测试我的报告应用程序。到目前为止,我有一些东西,

    Dim list As List(Of Object)
    Dim random As System.Random = New System.Random()
    For i As Integer = 1 To 100
        Dim obj As New Object
        If random.Next(0, 3) > 0 Then
            obj.Country = "China"
        Else
            obj.Country = "Japan"
        End If
        ...
        list.add(obj)
    Next

这很好用。但是我希望能够随机抽取更多的国家/地区,比如5(China, Japan, South Korea, North Korea, Taiwan),概率为0.4 : 0.3 : 0.1 : 0.1 : 0.1

我知道我可以扩展上面的If语句,但我真的希望避免凌乱的代码,因为目的只是生成虚拟数据。

虽然使用三元运算符可以简化上面的代码,但如果我需要在5个值之间随机选择,我该怎么办?除了If - Else声明之外还有其他选择吗?

1 个答案:

答案 0 :(得分:2)

Urm,到目前为止我能想到的最简单的解决方案是:

Dim list As List(Of Object)
Dim random As System.Random = New System.Random()
Dim Countries() As String = {"China", "China", "China", "China", _
                             "Japan", "Japan", "Japan", _
                             "South Korea", _
                             "North Korea", _
                             "Taiwan"}

For i As Integer = 1 To 100
    Dim obj As New Object
    obj.Country = Countries(random.Next(0, 10))
    ...
    list.add(obj)
Next