我有n
个元素,索引为0..(n-1)
。我想将元素分发到m
二进制文件中,如下所示:
⌊number_of_elements / number_of_bins⌋
和⌈number_of_elements / number_of_bins⌉
之间。更大的垃圾箱应该是第一位的。mod
和div
以及if
- 运算符。 示例:我有n=7
个元素和m=3
个分区。结果应该是这样的:
Bin 1: 0, 1, 2
Bin 2: 3, 4
Bin 3: 5, 6
答案 0 :(得分:0)
这是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;
更新:我在Python here中有几个示例实现。如果您对执行相同操作的不同方法感兴趣,请检查存储库的各个分支。