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>
Go 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
func pickFromShelves(wanted int, shelves []Shelf) []Pick {
}
Worked examples
| Call | Result |
|---|---|
pickFromShelves(12, []Shelf{Shelf{Code: "A1", Available: 5}, Shelf{Code: "A2", Available: 0}, Shelf{Code: "B3", Available: 20}}) | []Pick{Pick{Code: "A1", Taken: 5}, Pick{Code: "B3", Taken: 7}} |
pickFromShelves(4, []Shelf{Shelf{Code: "A1", Available: 10}}) | []Pick{Pick{Code: "A1", Taken: 4}} |
pickFromShelves(30, []Shelf{Shelf{Code: "A1", Available: 5}, Shelf{Code: "B3", Available: 6}}) | []Pick{Pick{Code: "A1", Taken: 5}, Pick{Code: "B3", Taken: 6}} |
pickFromShelves(0, []Shelf{Shelf{Code: "A1", Available: 5}}) | []Pick{} |
Hint
Carry a running "still needed" figure and stop as soon as it hits zero.
Reference solution in Go
func pickFromShelves(wanted int, shelves []Shelf) []Pick {
out := []Pick{}
need := wanted
for _, s := range shelves {
if need <= 0 {
break
}
take := need
if s.Available < take {
take = s.Available
}
if take <= 0 {
continue
}
out = append(out, Pick{Code: s.Code, Taken: take})
need -= take
}
return out
}