Exercise 14: Find Consecutive Numbers
Problem Statement
Create a function `findConsecutive(arr, count)` that finds sequences of consecutive numbers in array.
Example: findConsecutive([1, 2, 3, 5, 6, 7], 3) → [[1, 2, 3], [5, 6, 7]]
Sample Output:
findConsecutive([1, 2, 3, 5, 6, 7], 3) => [[1, 2, 3], [5, 6, 7]] findConsecutive([1, 2, 3, 4], 2) => [[1, 2], [2, 3], [3, 4]]
Solution
const findConsecutive = (arr, count) => {
const result = [];
for (let i = 0; i <= arr.length - count; i++) {
const seq = arr.slice(i, i + count);
if (seq.every((val, idx) => idx === 0 || val === seq[idx - 1] + 1)) result.push(seq);
}
return result;
};Explanation
Overall Goal:
- Array me consecutive sequences find karna.
Real world:
- Pattern detection: sequences identify.
- Data analysis: trends find.