检查数组是否包含与其他数组完全相同的序列 [英] Check if array contains exact same sequence as other array
问题描述
我有一个问题,我需要检查某个数组是否是较大数组的一部分,这很容易,但是我需要检查较大数组是否包含完全相同的序列。例如
I have a question, I need to check if some array is part of greater array, it would be rather easy but I need to check if the greater array contains exact same sequence. For example
int[] greaterArray = {8, 3, 4, 5, 9, 12, 6 ... n - elements}
int[] lesserArray = {3, 4, 5}
现在我需要知道较小的数组是否是此数组的一部分,但序列相同,因此它在较大的数组中包含3、4、5个彼此相邻的数组。
Now I need to know if lesser array is part of this array but with same sequence so It it contains 3, 4, 5 next to each other in greater array.
我尝试过:
var exists = greaterArray.Intersect(lesserArray).Any();
但是如果较小数组中的任何元素存在于较大数组中,而不是确切的序列,它将返回我的信息。有想法吗?
But it return me information if any element of lesser array exists in greater array, not exact sequence. Any ideas?
推荐答案
int[] greaterArray = {8, 3, 4, 5, 9, 12, 6};
int[] lesserArray = { 3, 4, 5 };
bool sequenceFound = false;
for (int i = 0; i <= greaterArray.Length - lesserArray.Length; i++)
{
if (greaterArray.Skip(i).Take(lesserArray.Length).SequenceEqual(lesserArray))
{
sequenceFound = true;
break;
}
}
if (sequenceFound)
{
//sequence found
}
else
{
//sequence not found
}
使用上面的代码。它从 greaterArray
中获取多个子序列,其长度等于 lesserArray
的长度,并将其与<$ c $匹配c> lesserArray 。
Use the above code. It takes multiple sub-sequences from greaterArray
of length equal to the length of lesserArray
and matches it with lesserArray
.
这篇关于检查数组是否包含与其他数组完全相同的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!