65

Given 2 int arrays e.g, foo and bar, what's the most 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?

shA.t
  • 16,580
  • 5
  • 54
  • 111
raklos
  • 28,027
  • 60
  • 183
  • 301
  • Is this homework? Are the arrays arbitrarily large, or smaller than, say, 100 elements? Have you tried anything besides brute-force foreach? – Adam Liss Feb 15 '10 at 12:57
  • 2
    no its not homework!... just figured there is probably a nice way of doing this. – raklos Feb 15 '10 at 13:54

7 Answers7

154

Using LINQ:

array1.Intersect(array2).Any()

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

shA.t
  • 16,580
  • 5
  • 54
  • 111
Olli
  • 1,995
  • 1
  • 13
  • 6
  • 4
    Using Any() assures that the intersection algorithm stops when the first equal object is found. – Olli Feb 15 '10 at 13:05
  • 12
    bear in mind that all of array1 is enumerated so you probably want the shorter array as array1 if possible – jk. Feb 15 '10 at 13:21
  • 4
    I never heard of the Intersect method so I had to look up what it does: http://msdn.microsoft.com/en-us/library/bb460136.aspx It basically gives you a list of items that are found in both of the compared arrays. With the any operator you then know if array1 and array2 have any of the same strings in this case. – Stefanvds Oct 21 '13 at 03:21
13

C#3:

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

C#4 parallel execution:

bool result = bar.AsParallel().Any(el => foo.AsParallel().Contains(el));
Alex Bagnolini
  • 21,990
  • 3
  • 41
  • 41
  • In my case foo is substring of el. so, `bool result = bar.Any(el => foo.Contains(el));` will not give required result. Any suggestion how to implement this query? – Irfan Y Nov 07 '17 at 18:38
  • In this case using `Any()` with `Contains()` is faster then other ways ;). – shA.t Aug 15 '18 at 05:12
2

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;
}
James Curran
  • 101,701
  • 37
  • 181
  • 258
2

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.

Gauravsa
  • 6,330
  • 2
  • 21
  • 30
0

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()));
-2
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);
}
----
  • 10
    Posting code that seems to be very specialized for one case is not very helpful without further explanation. – user11909 Feb 10 '20 at 12:16
  • See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. – the Tin Man Jan 29 '22 at 22:45
-3

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.

SF.
  • 13,549
  • 14
  • 71
  • 107
  • 2
    Good points, but it's not clear who you're talking to and it would have been helpful if you included some code directly related to OP q or a particular answer. – G. Stoynev Jan 16 '19 at 18:59
  • @G.Stoynev: I'm talking to the asker, which I believe what answers are supposed to be, and I doubt a nested 'foreach' comparison is complex enough to grant posting 'some code' - and unless OP qualifies the question with one of the 'special conditions' I'd mentioned there's no point guessing which would be applicable - for the general condition of single check on two arrays we know nothing about a nested foreach is the nicest solution. – SF. Jan 16 '19 at 20:59