Problems › JavaScript › monitoring
Should the alarm go off
A single spike is noise. An alert only fires when the reading stays over the limit for several samples in a row.
- A sample counts as a breach when it is strictly above the limit.
- The alarm fires as soon as that many breaches happen back to back.
- A run length of zero or less never fires.
alarmFires(readings: list<int>, limit: int, inARow: int) → bool
Where you start
function alarmFires(readings, limit, inARow) {
}
Worked examples
| Call | Result |
|---|---|
alarmFires([1,5,6,7,2], 4, 3) | true |
alarmFires([1,5,2,6,7], 4, 3) | false |
alarmFires([5,6], 4, 2) | true |
alarmFires([4,4,4], 4, 1) | false |
Hint
One counter, reset to zero the moment a reading comes back inside the limit.
Reference solution in JavaScript
function alarmFires(readings, limit, inARow) {
if (inARow <= 0) return false;
let run = 0;
for (const r of readings) {
run = r > limit ? run + 1 : 0;
if (run >= inARow) return true;
}
return false;
}