Given a large array of positive integer "weights", e.g. [ 2145, 8371, 125, 10565, ... ]
, and a positive integer "weight limit", e.g. 15000, I want to partition the weights into one or more smaller arrays, with the following criteria:
- I want to minimize the number of partitions.
- No single partition can add up to more than the weight limit. (Note that no single weight will exceed this limit.)
I suspect this problem has a high complexity class. As answers, I'm interested in:
- Optimal solutions
- Not-quite-optimal, but fast-running (approximate) solutions
Current non-optimal approach: (Basic greedy algorithm; JavaScript)
function minimizePartitions(weights, weightLimit) {
let currentPartition = [];
let currentSum = 0;
let partitions = [ currentPartition ];
for (let weight of weights) {
if (currentSum + weight > weightLimit) {
currentPartition = [];
currentSum = 0;
partitions.push(currentPartition);
}
currentPartition.push(weight);
currentSum += weight;
}
return partitions;
}
let weights = [3242, 987, 1222, 7299, 400, 10542, 10678, 513, 3977];
console.log(minimizePartitions(weights, 15000));