将整数m随机地分成n个部分,使得部分是整数,每个部分位于x和y之间

时间:2015-07-22 05:40:06

标签: vb.net math random

举个例子。我想随机分发100个巧克力给25个孩子。我不能给任何一个孩子超过10个巧克力。

所以这里m = 100,n = 25,x = 1,y = 12。

我已经检查了这些问题。

Dividing a number into m parts uniformly randomly

Dividing a number into random unequal parts

他们确实给出了一些想法,但在这些问题中没有指定x和y。

基本上,

1)巧克力总数= 100

2)我每个孩子只能给出最少1个和最多12个巧克力

3)巧克力应该分配给25个孩子

4)我不希望任何分布(统一或正常) - 它应该是纯粹随机的。 (如果其他所有方法都失败了,我愿意排除这种情况。)

Private Function divideUniformlyRandomly(n As Integer, m As Integer) As Integer()
    Dim rRandom As New Random
    Dim fences As Integer() = New Integer(m - 2) {}
    For i As Integer = 0 To m - 3
        fences(i) = rRandom.Next(0, n - 1)
    Next
    [Array].Sort(fences)

    Dim result As Integer() = New Integer(m - 1) {}
    result(0) = fences(0)
    For i As Integer = 1 To m - 3
        result(i) = fences(i + 1) - fences(i)
    Next
    result(m - 1) = n - 1 - fences(m - 2)

    Return result
End Function

这确实有效,但我也得到0和13。我无法确保x和y在这里。

1 个答案:

答案 0 :(得分:1)

给每个孩子x巧克力。这将让你用m - (n * x)随机分配。继续分发给巧克力少于y的儿童,直到没有巧克力为止。

Private Function divideUniformlyRandomly(n As Integer, m As Integer, x As Integer, y As Integer) As Integer()
    Dim rRandom As New Random
    Dim aResult As Integer() = New Integer(n - 1) {}

    Dim i As Integer = 0
    Dim remaining As Integer = m


    ' Every n must have a min of x.
    For i = 0 To n - 1
        aResult(i) = x
        remaining -= x
    Next

    ' distribute the remaining m over the children randomly
    While remaining > 0

        ' pick a child randomly
        i = rRandom.Next(0, n)

        ' if the child has less than y, give them one
        If aResult(i) < y Then
            aResult(i) += 1
            remaining -= 1
        End If

    End While

    ' Debug
    Dim sum As Integer = 0
    For i = 0 To n - 1
        Console.WriteLine("{0}: {1}", i, aResult(i))
        sum += aResult(i)
    Next

    Console.WriteLine("Sum: {0}", sum)

    divideUniformlyRandomly = aResult
End Function