0

使用具有这些功能的随机库:

randomChance(p) Returns true with the probability indicated by p.

randomInteger(low, high) Returns a random integer in the range low to high, inclusive.

什么是实现考虑百分比、1/4 或 1/3 等的“随机选择器”的最简单方法......我得到了一个带有键/值对的数组。例如"a",migth 的值为 2 且"b"值为 2。两者都有 1/2 的机会。

最大值将是数组的大小,因为它只包含唯一的项目。该randomChance()函数的范围介于0.0 - 1.01 = 100% 之间。如果我的数组大小是 4,那么“让 4 为 1”的最佳方法是什么。

4

2 回答 2

1

假设你有:

a = 2, b = 2, c = 1, d = 3

现在让它:

a = 2, b = 4, c = 5, d = 8

创建一个从 1 到 MaxVal 的随机数(最后一个键的值,在本例中为 8)。选择 Value >= RandomNum 的第一个 Key

编辑

我制作了一个小型 VB.Net 来展示算法及其工作原理。代码并不意味着:好的、优雅的、高性能的或可读的。

Module Module1

    Private Class Value
        Public vOrg, vRecalc, HitCount As Integer
        Public Key As String
        Public Sub New(s, v1, v2, c)
            Key = s : vOrg = v1 : vRecalc = v2 : HitCount = c
        End Sub
    End Class

    Sub Main()

        ' set initial values
        Dim KVP() As Value = {New Value("A", 2, 0, 0),
                              New Value("B", 2, 0, 0),
                              New Value("C", 1, 0, 0),
                              New Value("D", 3, 0, 0)}
        ' recalc values
        For i = 0 To KVP.Length - 1
            If i = 0 Then KVP(0).vRecalc = KVP(0).vOrg Else KVP(i).vRecalc = KVP(i).vOrg + KVP(i - 1).vRecalc
        Next
        ' do test
        Dim r As New Random
        Dim runs As Integer = 1000 * 1000, maxval As Integer = KVP(KVP.Length - 1).vRecalc
        For i = 1 To runs
            Dim RandVal = r.Next(1, maxval + 1)
            Dim chosen As Integer = (From j In Enumerable.Range(0, KVP.Length) Where KVP(j).vRecalc >= RandVal Take 1 Select j)(0)
            KVP(chosen).HitCount += 1
        Next
        ' ouput results
        For Each kv In KVP
            Console.WriteLine("{0} was chosen with {1:F3} propability, expected was {2:F3}", kv.Key, kv.HitCount / CDbl(runs), kv.vOrg / CDbl(maxval))
        Next

        Console.ReadLine()

    End Sub

End Module

输出样本:

A was chosen with 0.250 propability, expected was 0.250
B was chosen with 0.251 propability, expected was 0.250
C was chosen with 0.124 propability, expected was 0.125
D was chosen with 0.375 propability, expected was 0.375
于 2012-11-23T23:35:32.873 回答
1

只需将 randomChance() 结果和数组长度相乘即可。它会为您提供 [0,array_length-1] 范围内的索引,您可以使用它来访问数组

array_index = (unsigned int)(randomChance(p) * (array_length - 1));

在您的示例中,也许您的意思是“让 3 成为 1”(而不是 4)。长度为 4 的数组的最后一个索引是 3。

于 2012-11-23T23:41:23.570 回答