For instance: I have array
var src = new byte[] {1, 2, 3, 4, 5};
var tag = new byte[] {3, 4};
Who know fast method to find index of tag's array? I need something as following:
int FindIndexOfSeq(byte[] src, byte[] sequence);
a sequence can be in more than one times in src.
Solution: How to find index of sublist in list?
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second array.
I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.
The best you can get is O(m), but that I slightly complex implementation. If you satisfy with a solution that has O(m*n) as worst case you can go with the solution below. If your sequences are ordered and the starting item in the tag
array is only present one time in src
this will also result in O(m).
class Program
{
static void Main(string[] args)
{
var src = new byte[] { 1, 2, 3, 4, 5 };
var tag = new byte[] { 3, 4 };
var index = FindIndexOfSeq(src, tag);
Console.WriteLine(index);
Console.ReadLine();
}
static int FindIndexOfSeq<T>(T[] src, T[] seq)
{
int index = -1;
for (int i = 0; i < src.Length - seq.Length + 1; i++)
{
bool foundSeq = true;
for (int j = 0; j < seq.Length; j++)
{
foundSeq = foundSeq && src[i + j].Equals(seq[j]);
}
if (foundSeq)
{
index = i;
break;
}
}
return index;
}
}
I assumed the sequence have to be in that order and I have only compiled it in firefox, so not sure if it works :). Also, I made it generic so it handles any type of arrays not just bytes.
UPDATE: The updated code compiles and work... or my simple test worked.
Here's one way to the get the index
for (int i = 0; i < (src.Length - tag.Length); i++ )
{
if (tag.SequenceEqual(src.Skip(i).Take(tag.Length)))
Console.WriteLine("It's at position " + i);
}
Unfortunately it's very slow.
If you just want to know if all of items in tag
can be found in src
(in any order) then
var src = new byte[] { 1, 2, 3, 4, 5 };
var tag = new byte[] { 4, 3 };
if (src.Intersect(tag).Count() == tag.Length)
Console.WriteLine("tag can be found in src!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With