I'm seeking for a solution to split a list of items with varying sizes into N number of similarly-sized groups while preserve items order.
That it is a Johnson's algorithm or Bin Packing. Still I dont know how to implement it for N-groups and preserve items order.
Example of distributing into 3 groups:
Items to distribute:
- Item A - size 5
- Item B - size 1
- Item C - size 8
- Item D - size 2
- Item E - size 3
Desired output:
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);