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
C# 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.
Where you start
public bool AlarmFires(List<int> readings, int limit, int inARow) {
}
Worked examples
| Call | Result |
|---|---|
AlarmFires(new List<int> { 1, 5, 6, 7, 2 }, 4, 3) | true |
AlarmFires(new List<int> { 1, 5, 2, 6, 7 }, 4, 3) | false |
AlarmFires(new List<int> { 5, 6 }, 4, 2) | true |
AlarmFires(new List<int> { 4, 4, 4 }, 4, 1) | false |
Hint
One counter, reset to zero the moment a reading comes back inside the limit.
Reference solution in C#
public bool AlarmFires(List<int> readings, int limit, int inARow) {
if (inARow <= 0) return false;
int run = 0;
foreach (var r in readings) {
run = r > limit ? run + 1 : 0;
if (run >= inARow) return true;
}
return false;
}