How to determine that one array is part of another?

For example: I have an array

var src = new byte[] {1, 2, 3, 4, 5};
var tag = new byte[] {3, 4};

Who knows a quick method for finding the index of a tag array? I need something like the following:

int FindIndexOfSeq(byte[] src, byte[] sequence);

the sequence can be more than once in src.

How to find the index of a list in a list?

+5
source share
5 answers
int FindIndexOfSeq<T>(byte[] src, byte[] tag)
{
    Int32 tagCount = tag.Count();            

    // If `tag` is not empty and `src` contains `tag`
    if (tagCount > 0 && src.Intersect(tag).Count() == tagCount)
    {
        // Find index of first element in `tag`
        Int32 tagStartIndex = Array.IndexOf(src, tag.First());

        // Get the matching slice of `tag` from `src`
        var newSrc = src.Skip(tagStartIndex).Take(tag.Count()).ToList();

        // Zip them together using their difference
        var sum = Enumerable.Zip(tag, newSrc, (i1, i2) => Convert.ToInt32(i2 - i1)).Sum();

        // If total of their differences is zero, both sequences match
        if (sum == 0)
        {
            // return starting index of `tag` in `src`
            return tagStartIndex;
        }
    }

    // return `Not Found`
    return -1;
}
+1
source

Here is one way to 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 at position " + i);
}

Unfortunately, this is very slow.

If you just want to find out if all the elements can be found in tagin 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!");
+2
source

, , O (m), . , O (m * n) , . , tag src, 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;
    }
}

, , firefox, , :). , , , .

: ... .

+2

.

?

0

All Articles