9. Split an Order Across Warehouses
A retailer ships from several warehouses. Every extra package adds shipping cost and annoys the customer ("why did I get three boxes?"). The fulfillment team's rule: use as few warehouses as possible, and among options with the same number of warehouses, prefer the ones closest to the customer.
If the whole order cannot be filled, ship what is available from the nearest warehouses first and backorder the rest. A retailer has at most 8 warehouses, so checking every combination is acceptable.
Your task:
Write planFulfillment(orderLines, warehouses) and return { shipments, backordered }.
Rules:
- orderLines is a list of { sku, quantity }. Lines with quantity 0 are ignored. warehouses is a list of { id, distanceKm, stock: { [sku]: qty } }, in any order. Distances are all different.
- If some set of warehouses can fill the whole order together, pick the set with the fewest warehouses. Break ties by the smallest total distance.
- Inside the chosen set (or across all warehouses when no set can fill the order), allocate each line from the nearest warehouse first, taking as much as it has, then the next nearest.
- shipments is a list of { warehouseId, items: [{ sku, quantity }] } ordered by distance. Items follow the order-line order. Leave out empty shipments.
- backordered is a list of { sku, quantity } in order-line order, or [].
Notes:
- The helper combinations(items, size) returns every group of size elements, keeping their order.
Helpers you can use
These functions are already defined. Call them from your code; you don't need to copy them.
combinations(items, size) → any[][]Every group of `size` elements, in order. combinations([a, b, c], 2) → [[a, b], [a, c], [b, c]].
Show the helper code
/** Every group of `size` elements of `items`, keeping their order. */
function combinations(items, size) {
const result = [];
const pick = (start, group) => {
if (group.length === size) {
result.push([...group]);
return;
}
for (let i = start; i < items.length; i++) {
group.push(items[i]);
pick(i + 1, group);
group.pop();
}
};
pick(0, []);
return result;
}Examples
Example 1
- Input
orderLines = [{ sku: "A", quantity: 3 }, { sku: "B", quantity: 2 }]warehouses = [ { id: "W1", distanceKm: 5, stock: { A: 3 } }, { id: "W2", distanceKm: 12, stock: { B: 2 } }, { id: "W3", distanceKm: 30, stock: { A: 5, B: 5 } } ]
- Output
{ shipments: [ { warehouseId: "W3", items: [{ sku: "A", quantity: 3 }, { sku: "B", quantity: 2 }] } ], backordered: [] }
- Explanation
- One box from a farther warehouse beats two boxes from nearer ones.
Solution
Write planFulfillment. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.
Test Results
Click "Run Code" to test your solution.