Set L = sum of lengths
While L > 0
Get largest box B where size S <= L OR smallest box
set numB = Floor division L / B OR 1
store numB of B
Subtract numB * B from L
you’ll need some adjustments for a case where you might have waste (ie need 4 feet of cable but smallest box is 5)
if I were to javascript it:
function getBoxes(lengths, boxes) {
// sort descending
boxes = boxes.sort((b1, b2) => b2 - b1);
// get the smallest box (needed later)
const minB = boxes[boxes.length - 1];
// create an object to store my results;
const boxResult = boxes.reduce((acc, b) => Object.assign(acc, {[b]: 0}), {});
// sum lengths
let L = lengths.reduce((sum, l) => sum += l, 0);
while (L > 0) {
// get first box less than or equal to L or smallest box
const B = boxes.find(b => b <= L) || minB;
// get floor division or 1
const numB = Math.floor(L / B) || 1;
// store that number of that box (adding for waste case)
boxResult[B] += numB;
// subtract from L
L -= numB * B;
}
// done
return boxResult;
}
const lengths = [1, 1, 2, 3, 4, 5, 6, 7, 5, 4, 3, 2];
const boxes = [10, 5, 20];
const result = getBoxes(lengths, boxes);
console.log(result);
7
solved algorithm to find the number of boxes needed for different lengths of cable [closed]