【问题标题】:Randomly divide a whole number m into n parts such that the parts are whole numbers and each part lies between x and y将一个整数 m 随机分成 n 个部分,使得这些部分是整数,并且每个部分都位于 x 和 y 之间
【发布时间】:2015-07-22 15:11:29
【问题描述】:

举个例子。我想随机分发 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 在这里。

【问题讨论】:

  • 先给我们你的尝试。
  • 我不想要任何分布(均匀或正态)——它应该是纯粹随机的。”——这没有意义。

标签: vb.net math random


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2018-12-03
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多