Drill

ProblemsC# › inventory

Pick an order off the shelves

mediuminventoryArraysGreedySimulationC#

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>

C# 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

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

Worked examples

CallResult
PickFromShelves(12, new List<Shelf> { new Shelf("A1", 5), new Shelf("A2", 0), new Shelf("B3", 20) })new List<Pick> { new Pick("A1", 5), new Pick("B3", 7) }
PickFromShelves(4, new List<Shelf> { new Shelf("A1", 10) })new List<Pick> { new Pick("A1", 4) }
PickFromShelves(30, new List<Shelf> { new Shelf("A1", 5), new Shelf("B3", 6) })new List<Pick> { new Pick("A1", 5), new Pick("B3", 6) }
PickFromShelves(0, new List<Shelf> { new Shelf("A1", 5) })new List<Pick> { }

Hint

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

Reference solution in C#
public List<Pick> PickFromShelves(int wanted, List<Shelf> shelves) {
    var result = new List<Pick>();
    int need = wanted;
    foreach (var s in shelves) {
        if (need <= 0) break;
        int take = Math.Min(need, s.Available);
        if (take <= 0) continue;
        result.Add(new Pick(s.Code, take));
        need -= take;
    }
    return result;
}

The same problem in another language

More inventory problems in C#