function packBoxes(boxes) { // Sort boxes by volume in descending order boxes.sort((a, b) => b.volume - a.volume);
// Add the largest box to the list of packed boxes const packedBoxes = [boxes.shift()];
// Initialize the dimensions of the containing box let maxWidth = packedBoxes[0].width; let maxHeight = packedBoxes[0].height; let maxDepth = 0;
// Pack the remaining boxes into the containing box for (let box of boxes) { // Check if the box fits in the remaining space if (box.width <= maxWidth && box.height <= maxHeight && box.depth <= (maxDepth + packedBoxes[0].depth)) { // Update the dimensions of the remaining space maxDepth += box.depth; } else { // Add the current packed boxes to the result packedBoxes.push({ width: maxWidth, height: maxHeight, depth: maxDepth });
// Update the dimensions of the containing box
maxWidth = box.width;
maxHeight = box.height;
maxDepth = box.depth;
}
}
// Add the last set of packed boxes to the result packedBoxes.push({ width: maxWidth, height: maxHeight, depth: maxDepth });
// Calculate the dimensions of the containing box const containerWidth = packedBoxes.reduce((acc, box) => acc + box.width, 0); const containerHeight = Math.max(...packedBoxes.map(box => box.height)); const containerDepth = Math.max(...packedBoxes.map(box => box.depth));
// Calculate the location of each small box within the containing box const smallBoxes = []; let x = 0; let y = 0; let z = 0;
for (let box of packedBoxes) { const boxWidth = box.width; const boxHeight = box.height; const boxDepth = box.depth;
for (let smallBox of box.boxes) {
smallBoxes.push({
id: smallBox.id,
x: x,
y: y + smallBox.y,
z: z + smallBox.z
});
if (y + smallBox.y + smallBox.height > boxHeight) {
x += smallBox.width;
y = 0;
}
y += smallBox.y + smallBox.height;
if (z + smallBox.z + smallBox.depth > boxDepth) {
x += smallBox.width;
y = 0;
z = 0;
}
z += smallBox.z + smallBox.depth;
}
x += boxWidth;
y = 0;
z = 0;
}
// Return the results return { containerWidth: containerWidth, containerHeight: containerHeight, containerDepth: containerDepth, smallBoxes: smallBoxes }; }
// Example usage const boxes = [ { id: 1, width: 4, height: 5, depth: 6 }, { id: 2, width: 3, height: 5, depth: 4 }, { id: 3, width: 2, height: 3, depth: 2 }, { id: 4, width: 3, height: 3, depth: 3 }, { id: 5, width: 2, height: 2, depth: 2 } ];
const result = packBoxes(boxes);
console.log('Container dimensions:');
console.log(Width: ${result.containerWidth});
console.log(Height: ${result.containerHeight});
console.log(Depth: ${result.containerDepth});
console.log('Small box coordinates:');
for (let box of result.smallBoxes) {
console.log(Box ${box.id}: (${box.x}, ${box.y}, ${box.z}));
}