Find a pass of sequential values ​​in an int array

Let's say I have this integer array of single integer elements:

111100010011010

      

I would like to know if this array exists 0000

, which obviously does not, but 000

does. The same applies to other lengths of successive runs.

I know it's easy to do this with strings, there are built-in functions for that, but is there something built in that does what I want to do?

Or is there another simple method that I forgot? All I can think of is complex inefficient algorithms going through an array and storing the values ​​in a temporary other array.

+3


source to share


2 answers


You don't need to store the values ​​in a temporary array.

All you have to do is keep track of the largest length found (initially zero) and the location of its first element (initially NULL if you specified a pointer).

Then walk through the array until you find the value of interest. Count the number of consecutive events. If this number is greater than the maximum length found, set a location to indicate the first found.

Repeat until you reach the end of the array.



Done. If the found longest length is zero, it means that there were no values ​​for the desired value.

No, I will not write the code for the above. The description of the approach is sufficient.

There are also many alternatives using standard algorithms.

+2


source


For writing only, another way is to use std :: search .

#include <algorithm>
using namespace std;

const int elements[] = { 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0 };
const int test1[] = { 0, 0, 0, 0 };
const int test2[] = { 0, 0, 0 };

auto it1 = std::search(begin(elements), end(elements), begin(test1), end(test1));
auto it2 = std::search(begin(elements), end(elements), begin(test2), end(test2));

std::cout << "Test 0000: " << (it1 == end(elements) ? "no" : "yes") << "\n";
std::cout << "Test 000: " << (it2 == end(elements) ? "no" : "yes") << "\n";

      

Prints out:



Test 0000: no
Test 000: yes

      

It's even easier if your array is a standard container like std :: array or vector.

+2


source







All Articles