Drill

ProblemsGo › patterns

How often the load crossed the line

mediumpatternsSliding windowArraysGo

Capacity planning counts how many fixed-length stretches of the day carried at least a given amount of work.

windowsOverLimit(load: list<int>, runLength: int, limit: 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 windowsOverLimit(load []int, runLength int, limit int) int {
	
}

Worked examples

CallResult
windowsOverLimit([]int{1, 2, 3, 4, 5}, 2, 5)3
windowsOverLimit([]int{1, 1, 1}, 2, 10)0
windowsOverLimit([]int{5, 5, 5}, 1, 5)3
windowsOverLimit([]int{1, 2}, 3, 1)0

Hint

Slide one total across the list rather than re-summing each window, and test it at every stop.

Reference solution in Go
func windowsOverLimit(load []int, runLength int, limit int) int {
	if runLength <= 0 || len(load) < runLength {
	    return 0
	}
	window := 0
	for i := 0; i < runLength; i++ {
	    window += load[i]
	}
	hits := 0
	if window >= limit {
	    hits = 1
	}
	for i := runLength; i < len(load); i++ {
	    window += load[i] - load[i-runLength]
	    if window >= limit {
	        hits++
	    }
	}
	return hits
}

The same problem in another language

More patterns problems in Go