Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is fastest way to find number of matches between arrays?

Currently, I am testing every integer element against each other to find which ones match. The arrays do not contain duplicates within their own set. Also, the arrays are not always equal lengths. Are there any tricks to speed this up? I am doing this thousands of times, so it's starting to become a bottle neck in my program, which is in C#.

like image 724
John Sheares Avatar asked Apr 10 '10 18:04

John Sheares


People also ask

How do you compare two arrays to find matches?

JavaScript finding non-matching values in two arrays The code will look like this. const array1 = [1, 2, 3, 4, 5, 6]; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const output = array2. filter(function (obj) { return array1. indexOf(obj) === -1; }); console.


2 Answers

You could use LINQ:

var query = firstArray.Intersect(secondArray);

Or if the arrays are already sorted you could iterate over the two arrays yourself:

int[] a = { 1, 3, 5 };
int[] b = { 2, 3, 4, 5 };

List<int> result = new List<int>();
int ia = 0;
int ib = 0;
while (ia < a.Length && ib < b.Length)
{
    if (a[ia] == b[ib])
    {
        result.Add(a[ia]);
        ib++;
        ia++;
    }
    else if (a[ia] < b[ib])
    {
        ia++;
    }
    else
    {
        ib++;
    }
}
like image 165
Mark Byers Avatar answered Oct 28 '22 20:10

Mark Byers


Use a HashSet

var set = new HashSet<int>(firstArray);
set.IntersectWith(secondArray);

The set now contains only the values that exist in both arrays.

like image 27
Josh Avatar answered Oct 28 '22 20:10

Josh