随机函数和计算百分比

时间:2012-11-23 23:26:59

标签: math random

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

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.0之间,其中1 = 100%。如果我的数组大小是4,那么“让4为1”的最佳方法是什么。

2 个答案:

答案 0 :(得分:1)

让我们说:

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

现在成功:

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

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

修改

我做了一个小的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

答案 1 :(得分:1)

将randomChance()结果与数组长度相乘。它将为您提供可用于访问数组的范围[0,array_length-1]中的索引

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

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