Problems › JavaScript › patterns
How often the load crossed the line
Capacity planning counts how many fixed-length stretches of the day carried at least a given amount of work.
- Every run of exactly `runLength` consecutive entries counts as one window, overlapping ones included.
- A window counts when its total is greater than or equal to the limit.
- If the window does not fit in the data, or the size is not positive, the answer is 0.
windowsOverLimit(load: list<int>, runLength: int, limit: int) → int
Where you start
function windowsOverLimit(load, runLength, limit) {
}
Worked examples
| Call | Result |
|---|---|
windowsOverLimit([1,2,3,4,5], 2, 5) | 3 |
windowsOverLimit([1,1,1], 2, 10) | 0 |
windowsOverLimit([5,5,5], 1, 5) | 3 |
windowsOverLimit([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 JavaScript
function windowsOverLimit(load, runLength, limit) {
if (runLength <= 0 || load.length < runLength) return 0;
let window = 0;
for (let i = 0; i < runLength; i += 1) window += load[i];
let hits = window >= limit ? 1 : 0;
for (let i = runLength; i < load.length; i += 1) {
window += load[i] - load[i - runLength];
if (window >= limit) hits += 1;
}
return hits;
}