Reputation: 21
I have some arrays filled with 1 and 0. Is there any easy way to find, for example, 10 fields next to each other with value 1?
Something like: if (array[i ... i+10] = 1) -> do some stuff?
I know that I can use for
to do it, but I have a huge multiple array and this will by very helpful.
Upvotes: 1
Views: 1208
Reputation: 149068
You can do this pretty easily with a for loop:
int c = 0;
for (int i = 0; i < myArray.Length; i++)
{
c = (myArray[i] == 1) ? c + 1 : 0;
if (c >= 10)
{
// do stuff
}
}
Here's another way using Linq:
var indexes =
from i in Enumerable.Range(0, myArray.Length - 10)
where myArray.Skip(i).Take(10).All(x => x == 1)
select i;
foreach(var i in indexes)
{
// do stuff
}
This will return all indexes of myArray
where the element at that index and the elements next 9 indexes are all equal to 1. However, this method is somewhat less efficient than the simple for-loop because it potentially checks each item more than once.
If you prefer fluent syntax:
var indexes = Enumerable.Range(0, myArray.Length - 10)
.Where(i => myArray.Skip(i).Take(10).All(x => x == 1));
foreach(var i in indexes)
{
// do stuff
}
Upvotes: 7
Reputation: 8192
If I understand your question right, you want to do something called pattern matching.
There are many algorithms out there. A first starting point is this page here
From the algorithms the Turbo-Boyer-Moore is one that is performing best.
But you can also handle that problem with a data structure, like a suffix tree: see this article on suffix trees (or simply called Trie)
Here is an implementation of the Boyer-Moore algorithm Codeproject article on Boyer-Moore
Upvotes: 1