开发者

How to check if an array contains any item of another array

开发者 https://www.devze.com 2022-12-20 09:24 出处:网络
Given 2 int arrays e.g, foo and bar, what\'s the most 开发者_JAVA百科efficient way to check that the array bar contains at least one item that foo contains. should return true/false.

Given 2 int arrays e.g, foo and bar, what's the most 开发者_JAVA百科efficient way to check that the array bar contains at least one item that foo contains. should return true/false.

I'm suspecting nested foreach but just wondering if there's a nicer way?


Using LINQ:

array1.Intersect(array2).Any()

Note: Using Any() assures that the intersection algorithm stops when the first equal object is found.


C#3:

bool result = bar.Any(el => foo.Contains(el));

C#4 parallel execution:

bool result = bar.AsParallel().Any(el => foo.AsParallel().Contains(el));


Yes nested loops, although one is hidden:

bool AnyAny(int[] A, int[]B)
{
    foreach(int i in A)
       if (B.Any(b=> b == i))
           return true;
    return false;
}


Another solution:

var result = array1.Any(l2 => array2.Contains(l2)) == true ? "its there": "not there";

If you have class instead of built in datatypes like int etc, then need to override Override Equals and GetHashCode implementation for your class.


Distinct is optional depends of your first array (with or without unique value)...

String[] A = new String[] {"2","1","3","2"};
String[] B = new String[] {"1","2", "3", "3", "1", "1", "2"};
Console.WriteLine("A values: "+String.Join(", ",A));
Console.WriteLine("B values: "+String.Join(", ",B));
Console.WriteLine("Comparison A and B result: "+ A.Distinct().Intersect(B).SequenceEqual(A.Distinct()));


static void Main(string[] args)


    int[] arr1 = { 16, 48, 40, 32, 5, 7 };
    int[] arr2 = { 48, 32, 16, 40, 56, 72, 16, 16, 16, 16, 16, 5, 7, 6, 56 };
    int k = 0;
    for (int i = 0; i < arr1.Length; i++)
    {

        for (int j = 0; j < arr2.Length; j++)
        {

            if (arr1[i] == arr2[j])
            {
                k++;
                break;
            }

        }

    }
    if (arr1.Length == k)
    {
        Console.WriteLine(true);
    }
    else
        Console.WriteLine(false);
}
----


For one-shot random-array approach, your method seems to be the fastest. There are methods that would make it way more efficient if one or both matrices are sorted, their upper/lower bounds are known, or one of them changes way more rarely than the other one and you perform many checks. Thing is you can prepare various hashes, indices and hints that will optimize the search to nearly nothing, but the process of indexing alone will usually take more than a single search.

0

精彩评论

暂无评论...
验证码 换一张
取 消