-2

I need a way to find how many common elements in between two arrays.

Suppose that I have:

a = {1,2,3,4,5,6,7,8,9}
b = {2,4,6,8,10} 

So the result would be 4.

I need it to be effective with very large array like arrays of length 1300000. I have tried the intersect method but it gave me a wrong number such as 256 or 11 and tried with method Zip but it's too slow.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
devloper
  • 13
  • 1
  • 5
  • 3
    how did you use Intersect? – Saverio Terracciano Jun 21 '14 at 11:32
  • 1
    Don't think that Intersect does not work... – Uriil Jun 21 '14 at 11:33
  • 3
    Did you use `a.Intersect(b).Count()`? – Douglas Jun 21 '14 at 11:40
  • 1
    Can you post some code - what you already have / have tried? – Unihedron Jun 21 '14 at 11:41
  • @Douglas yes as i said i my questio it gave me wrong number – devloper Jun 21 '14 at 11:51
  • `int equalElements = ival.Zip(jval, (iv, jv) => iv == jv).Count(eq => eq);` while ival , jval are arrays of type byte @Unihedron – devloper Jun 21 '14 at 11:52
  • @SaverioTerracciano `ival.Intersect(jval).Count();` **ival** and **jval** are arrays – devloper Jun 21 '14 at 11:54
  • ` byte[] ival=mydictionary.Values.ToArray()[i]; byte[] jval=mydictionary.Values.ToArray()[j]; var cou =ival.Intersect(jval).Count();` note that ival and jval have length of 1300000 and have more than 50000 at least common element ,, i and j are for loop variables – devloper Jun 21 '14 at 12:06
  • You're calling ToArray() in every loop. Every call will copy all the items into a new array. Since the Dictionary is very large, it's better to call it just once and loop through the array. This probably won't solve your problem though, since ToArray should produce the same array every time if nothing has changed inside the Dictionary. Are you adding or removing items inside the loop? – Dennis_E Jun 21 '14 at 12:29
  • so what do you suggest to compare the values of each dictionary ? note that the loop is very important and i can't reomve it – devloper Jun 21 '14 at 12:36
  • I just meant to create one array instead of a new one every loop: var array = mydictionary.Values.ToArray(); and then use the array variable in the loop: byte[] ival = array[i]; byte[] jval = array[j]; – Dennis_E Jun 21 '14 at 13:09

1 Answers1

0

Try to use Intersect

List<int> a = new List<int> {1,2,3,4,5,6,7,8,9};
List<int> b = new List<int>{2,4,6,8,10} ;

int CommonNumber = a.Intersect(b).Count();
MRebai
  • 5,344
  • 3
  • 33
  • 52