Drill

ProblemsGo › machines

Which station has the least work

hardmachinesHash mapsArraysSortingGo

Jobs are queued against stations on a line. Find the station currently carrying the fewest hours so the next job can be routed there.

leastLoadedStation(jobs: list<Job>, stationCount: int) → int

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 leastLoadedStation(jobs []Job, stationCount int) int {
	
}

Worked examples

CallResult
leastLoadedStation([]Job{Job{Station: 0, Hours: 10}, Job{Station: 1, Hours: 5}, Job{Station: 0, Hours: 2}}, 2)1
leastLoadedStation([]Job{Job{Station: 0, Hours: 3}, Job{Station: 1, Hours: 3}}, 2)0
leastLoadedStation([]Job{Job{Station: 5, Hours: 10}}, 3)0
leastLoadedStation([]Job{}, 4)0

Hint

Tally per station in an array, then walk the array keeping a running best index.

Reference solution in Go
func leastLoadedStation(jobs []Job, stationCount int) int {
	if stationCount <= 0 {
		return 0
	}
	totals := make([]int, stationCount)
	for _, j := range jobs {
		if j.Station < 0 || j.Station >= stationCount {
			continue
		}
		totals[j.Station] += j.Hours
	}
	best := 0
	for i := 1; i < stationCount; i++ {
		if totals[i] < totals[best] {
			best = i
		}
	}
	return best
}

The same problem in another language

More machines problems in Go