Drill

ProblemsJava › inventory

Pick an order off the shelves

mediuminventoryArraysGreedySimulationJava

A picker needs a quantity of one part, and it is spread across several shelves. Walk the shelves in the order given and take what you can from each until the order is filled.

pickFromShelves(wanted: int, shelves: list<Shelf>) → list<Pick>

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Pick> pickFromShelves(int wanted, List<Shelf> shelves) {
    
}

Worked examples

CallResult
pickFromShelves(12, Main.<Shelf>ls(new Shelf("A1", 5), new Shelf("A2", 0), new Shelf("B3", 20)))Main.<Pick>ls(new Pick("A1", 5), new Pick("B3", 7))
pickFromShelves(4, Main.<Shelf>ls(new Shelf("A1", 10)))Main.<Pick>ls(new Pick("A1", 4))
pickFromShelves(30, Main.<Shelf>ls(new Shelf("A1", 5), new Shelf("B3", 6)))Main.<Pick>ls(new Pick("A1", 5), new Pick("B3", 6))
pickFromShelves(0, Main.<Shelf>ls(new Shelf("A1", 5)))Main.<Pick>ls()

Hint

Carry a running "still needed" figure and stop as soon as it hits zero.

Reference solution in Java
List<Pick> pickFromShelves(int wanted, List<Shelf> shelves) {
    List<Pick> out = new ArrayList<>();
    int need = wanted;
    for (Shelf s : shelves) {
        if (need <= 0) break;
        int take = Math.min(need, s.available);
        if (take <= 0) continue;
        out.add(new Pick(s.code, take));
        need -= take;
    }
    return out;
}

The same problem in another language

More inventory problems in Java