我正在寻找一种解决方案,将不同大小的项目列表拆分成N个大小相似的组,同时保持项目顺序.
这是一个约翰逊算法或宾格包装.我仍然不知道如何为N组实现它,并保持项目顺序.
分成3组的示例:
要分发的项目:
- 项目A-尺码5
- 物品B-尺码1
- 物品C-尺码8
- 物品D-尺码2
- 项目E-尺寸3
请注意,情况并非如此.
Group 1 (total size 6): Item A, Item B
Group 2 (total size 8): Item C
Group 3 (total size 5): Item D, Item E
function distributeItems(items, numGroups) {
const totalItems = items.length;
const groupSizes = Array.from({ length: numGroups }, () => 0);
const groups = Array.from({ length: numGroups }, () => []);
for (let i = 0; i < totalItems; i++) {
const currentItem = items[i];
let minSizeIndex = 0;
for (let j = 1; j < numGroups; j++) {
if (groupSizes[j] < groupSizes[minSizeIndex]) {
minSizeIndex = j;
}
}
groups[minSizeIndex].push(currentItem);
groupSizes[minSizeIndex] += currentItem.size;
}
for (let i = 0; i < numGroups; i++) {
console.log(`Group ${i + 1} (total size ${groupSizes[i]}): ${groups[i].map(item => item.title).join(', ')}`);
}
}
const items = [
{ title: 'Item A', size: 5 },
{ title: 'Item B', size: 1 },
{ title: 'Item C', size: 8 },
{ title: 'Item D', size: 2 },
{ title: 'Item E', size: 3 },
];
distributeItems(items, 3);