【问题标题】:Algorithm for generating 'balls in bins' outcomes with limits on bin size?生成“垃圾箱中的球”结果的算法对垃圾箱大小有限制?
【发布时间】:2021-04-20 23:21:59
【问题描述】:

假设我们有 N 个球和 M 个箱子可以放入它们。可以使用“星条”方法Integer Equations - Stars and Bars 找到此结果的数量。我们还可以使用itertools 包计算所有实际结果,并使用sympy.utilities.iterables.multiset_permutations 获得独特的结果。

如果我们将 bin 大小限制为 [0, N] 上的某个任意数字,您如何有效地计算所有可能的结果?有没有比在没有 bin 大小的情况下计算所有结果然后消除无效结果更好的方法?

对于 N = 2 和 M = 3,结果为 {200, 110, 020, 011, 101, 002}

例如,如果 N = 3 和 M = 3,则结果为 {300, 210, 120, 021, 012, 030, 201, 102, 003, 111}。但是,如果我们想要一些数组 b=[3,3,0] 指定最大 bin 大小以便唯一有效的结果是 {300, 210, 120, 030}

【问题讨论】:

标签: python permutation itertools combinatorics


【解决方案1】:

您可以使用递归方法将 0 到最大的球放在第一个箱子上,然后将剩余的球递归到其余的箱子上:

def ballPlacing(N,B):
    if N <= 0: return int(N==0)
    if len(B) == 1:
        return int(N<=B[0])
    total = 0
    for c in range(min(N,B[0])+1):
        total += ballPlacing(N-c,B[1:])
    return total

print(ballPlacing(3,[3,3,3])) # 10
print(ballPlacing(3,[3,3,0])) # 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    相关资源
    最近更新 更多