2013-08-15 3 views
0

J'ai un tableau de 25 nombres et j'ai un autre tableau de 15 nombres. Quel est le moyen le plus rapide de trouver exactement (pas plus, pas moins) 5 correspondances des 15 nombres dans le tableau des 25 nombres?Vérifiez si dans un tableau d'entiers est exactement un nombre de correspondances dans C#?

Exemple:

int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 } 

int[] array2 = { 1, 2, 3, 4, 5, 36, 77, 88, 49, 50, 51, 52, 53, 54, 55 } 

int[] array3 = { 1, 2, 3, 4, 5, 6, 26, 17, 28, 29, 30, 31, 32, 33, 34 } 

int[] array4 = { 1, 2, 3, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 } 

dans l'exemple le array2 est le tableau valide, car il a exactement 5 matches, mais les array3 et array4 ne sont pas valides.

+1

-ce que tous vos tableaux toujours garantis à trier? La méthode devrait-elle retourner s'il y a exactement 5 correspondances entre deux tableaux, ou devrait-elle renvoyer les correspondances s'il y en a exactement 5? – Michelle

+1

En outre, avez-vous réellement _tried_ quoi que ce soit par vous-même? Incluez du code pour montrer que vous avez fait des efforts pour résoudre votre propre problème. – Michelle

+1

Tous les nombres sont-ils distincts dans tous les tableaux? Si c'est le cas, LINQ devrait rendre cela plutôt trivial. –

Répondre

2
int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; 
int[] array2 = { 1, 2, 3, 4, 5, 36, 77, 88, 49, 50, 51, 52, 53, 54, 55 }; 

int numMatches = array1.Intersect(array2).Count(); 
0
int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; 

int[] array2 = { 1, 2, 3, 4, 5, 36, 77, 88, 49, 50, 51, 52, 53, 54, 55 }; 

int[] array3 = { 1, 2, 3, 4, 5, 6, 26, 17, 28, 29, 30, 31, 32, 33, 34 }; 

int[] array4 = { 1, 2, 3, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 }; 

var matches = 
    from set1 in array1 
    join set2 in array2 on set1 equals set2 
    select set1; 
if (matches.Count() == 5) 
     return true; 
else 
     return false; 
0

Cette méthode ne fonctionne ne pas trop:

bool CompareCount(int[] array1, int[] array2, int count) 
{ 
    // Check that the arrays contain at least count of integers. 
    if (array1 == null || array1.length < count) return false; 
    if (array2 == null || array2.length < count) return false; 

    // Check that the first count integers are identical. 
    for(int i = 0; i < count; count++) 
     if (array1[i] <> array2[i]) return false; 
    // If one of the arrays only contains count integers, then its okay. 
    if (array1.length == count || array2.length == count) return true; 

    // If the next integers are different, then its okay. 
    return array1[count] != array2[count]; 
} 
Questions connexes