Pick an order off the shelves
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.
- Take as much as a shelf holds, but never more than is still needed.
- Skip shelves that would contribute nothing.
- If the shelves cannot cover it, take everything they have and stop there.
- A request of zero or less picks nothing.
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.
Where you start
public List<Pick> PickFromShelves(int wanted, List<Shelf> shelves) {
}
Worked examples
| Call | Result |
|---|---|
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;
}