根据索引将元素均衡分配到 bin

Balanced distribution of elements to bins based on index

我有 n 个索引为 0..(n-1) 的元素。我想像这样将元素分发到 m 个垃圾箱:

示例:我有 n=7 个元素和 m=3 个分箱。结果应该是这样的:

Bin 1: 0, 1, 2 
Bin 2: 3, 4
Bin 3: 5, 6

这是 Python 中的概念验证示例。

# Initialize
elements = [0, 1, 2, 3, 4, 5, 6];
n = len(elements); # Number of elements
m = 3; # Number of bins
bins = [[] for x in range(m)];

# Precalculate this
elementsPerBinCeil = n / m;
elementsPerBinFloor = n / m - 1;
# This is the bin number above which we have to use elementsPerBinFloor
cutoffNum = n % m;
i = 0; # This is which bin to assign the element to
# Assign all elements to a bin
for element in elements:
    bins[i].append(element);
    # Move to next bin
    if (i < cutoffNum and len(bins[i]) > elementsPerBinCeil):
        i += 1;
    elif (i >= cutoffNum and len(bins[i]) > elementsPerBinFloor):
        i += 1;

更新:我在Pythonhere中有几个示例实现。如果您对做同一件事的不同方法感兴趣,请检查存储库的各个分支。