Easy way to check an array for contiguous three or more numbers in Swift

c program to check consecutive numbers
find consecutive numbers in an array c#
swift array index
find consecutive numbers in an array python
swift array of objects
how to count consecutive numbers in java
swift initialize array with size
swift array size

Is there any easy way to check if an array contains contiguous value of three or more? e.g. `[4, 2, 1, 1, 1, 7, 4, 4, 4, 4]` contains two contiguous sequence of 1 and 4. To check I wish to give 1 and minimum allowed conjugation, in this case 2, it will just return `true`. Thanks.

Get Array Size in Swift - count function - Examples, How do I find the length of an array in Swift? We have discussed different solutions for distinct elements in below post. Check if array elements are consecutive. A simple solution is to first sort the array. Then traverse the array to check if all consecutive elements differ at most by one.

I think the simplest possible way is with the help of the reduce function. If you want you can extend the data structures, but I am not quite a fan of that. So here is a simple solution to your example

```    // example array
let a = [4, 2, 1, 1, 1, 7, 4, 4, 4, 4]

let minRepeats = 3      // desired min repeats
let elementToCheck = 4  // element to check

let m = a.reduce(0) { (initial: Int, el: Int) -> Int in
if initial >= minRepeats {
return initial
} else {
return el == elementToCheck ? initial + 1 : 0
}
}

// if m == minRepeats the check is positive, if m < minRepeats the check is negative
// let check = a.reduce(0){...} == minRepeats gives you the right result
// Thanks to user3441734 for the correction
```

Check if the array elements are consecutive, How do you know if an array has consecutive elements? Use the capacity and count properties to determine how many more elements the array can store without allocating larger storage. For arrays of most Element types, this storage is a contiguous block of memory. For arrays with an Element type that is a class or @objc protocol type, this storage can be a contiguous block of memory or an instance of NSArray.

The answers above were helpful but not quite as generic as I needed. Also, they are a little outdated, so for those who come across this requirement, here's a generic reusable Swift 4.2 implementation:

An extension on any `Collection` that returns an array of ranges representing the indices of consecutive elements in a collection matching a given predicate.