Drill

ProblemsGo › inventory

Pick an order off the shelves

mediuminventoryArraysGreedySimulationGo

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>

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.

Solve it in Python →

Where you start

func pickFromShelves(wanted int, shelves []Shelf) []Pick {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More inventory problems in Go