I got a question for an algorithm to divide a given array into the sub parts.
Here is the scenario.
I have 3 items to ship. Weights of items are [10 lb, 15 lb , 5 lb]
I need to calculate cases to package the order.
So for the example case, the possible cases would be
- 30 lb // one package
- 25 + 5 // two packages
- 10 + 20 // two packages
- 10 + 15 + 5 // three packages
Therefore, the output should be [ 30, [25,5], [10,20], [10,15,5] ] Can anyone please help me to figure out a good algorithm to simulate this model?
Here is my code
const input = [10, 15, 5];
function divideArray(array, length) {
const result = [];
function backtrack(startIndex, currentParts) {
if (currentParts.length === length) {
result.push([...currentParts]);
return;
}
for (
let i = startIndex;
i <= array.length - length + currentParts.length;
i++
) {
currentParts.push(array.slice(i, i + length));
backtrack(i + 1, currentParts);
currentParts.pop();
}
}
backtrack(0, []);
return result;
}
const subarrayLength = 2;
const dividedArrays = divideArray(input, subarrayLength);
console.log(dividedArrays);
Thank you!
I’ve tried to write a JS function using a recursion function but no luck
2
Answers
try that fixes:
If I understand you correctly the problem is to find all the ways of grouping objects in a collection.
In the trivial case (one object:A) the response would be
[A]
For two objects A,B the response would be
[A+B] or [A]+[B]
For three objects A,B,C the response would be
[A+B+C] or [A+B]+[C] or [A]+[B+C] or [A+C]+[B] or [A]+[B]+[C]
Is that a correct understanding of the problem?