web-dev-qa-db-fra.com

Java, trouver l'intersection de deux tableaux

J'ai déjà lu quelques autres threads de débordement de pile sur ceci:

pour trouver l'intersection de deux multisets en Java

Comment obtenir l'intersection de deux tableaux en tant que nouveau tableau?

public static int[] intersection (int [] x, int numELementsInX, int [] y, int numElementsInY) {

J'essaie d'examiner deux tableaux, ainsi que leur nombre d'éléments (numElementsInX et numElementsInY), et de retourner un nouveau tableau contenant les valeurs communes des tableaux x et y. Leur intersection.

Example,if x is{1,3,5,7,9}and y is{9,3,9,4} then
intersection(x, 5, y, 4} should return {3, 9} or {9, 3}

J'ai lu que je devais utiliser l'algorithme LCS. Quelqu'un peut-il me donner un exemple sur la façon de procéder? Le tableau et les valeurs du tableau sont initialisés et générés selon une autre méthode, puis transmis à l'intersection.

Toute aide/clarification est appréciée.

EDIT CODE

for (int i=0; i<numElementsInX; i++){
    for (int j=0; j<numElementsInY; j++){
        if (x[j]==x[i]) { //how to Push to new array?; 
        }
        else{
        }
    }
}
23
andrsnn

La solution la plus simple serait d'utiliser des ensembles, tant que vous ne vous souciez pas du fait que les éléments du résultat auront un ordre différent et que les doublons seront supprimés. Les tableaux array1 et array2 sont les sous-tableaux Integer[] des tableaux int[] donnés correspondant au nombre d'éléments que vous souhaitez traiter:

Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(array1));
Set<Integer> s2 = new HashSet<Integer>(Arrays.asList(array2));
s1.retainAll(s2);

Integer[] result = s1.toArray(new Integer[s1.size()]);

Ce qui précède renverra un Integer[]. Si nécessaire, il est simple de copier et de convertir son contenu en un int[].

44
Óscar López

Si vous êtes d'accord avec Java-8 , la solution la plus simple à laquelle je puisse penser consiste à utiliser des flux et un filtre. Une implémentation est la suivante:

public static int[] intersection(int[] a, int[] b) {
    return Arrays.stream(a)
                 .distinct()
                 .filter(x -> Arrays.stream(b).anyMatch(y -> y == x))
                 .toArray();
}
13
Bilesh Ganguly

Si vous ne souhaitez pas utiliser d'autres structures de données telles qu'un ensemble, alors l'idée de base est de vouloir parcourir les éléments de l'un des tableaux et voir pour chaque valeur si elle apparaît dans l'autre. Comment voyez-vous s'il apparaît dans l'autre tableau? Parcourez les éléments de l'autre tableau et, pour chacun d'entre eux, voyez si sa valeur est égale à la valeur que vous recherchez. Je suppose que vous serez mieux servi en essayant de résoudre ce problème vous-même au-delà de ce point si votre objectif en prenant le cours est d'apprendre à bien écrire en Java, mais si vous êtes bloqué, vous pourriez envisager de mettre à jour votre question avec le code. que vous avez écrit afin que vous puissiez obtenir des commentaires plus détaillés et des indicateurs dans la bonne direction.

2
tuckermi

Avec des éléments en double dans l'intersection de recherche de tableau. 

    int [] arr1 = {1,2,2,2,2,2,2,3,6,6,6,6,6,6,};
    int [] arr2 = {7,5,3,6,6,2,2,3,6,6,6,6,6,6,6,6,};

    Arrays.sort(arr1);
    Arrays.sort(arr2);
    ArrayList result = new ArrayList<>();
    int i =0 ;
    int j =0;
    while(i< arr1.length && j<arr2.length){
    if (arr1[i]>arr2[j]){
        j++;

    }else if (arr1[i]<arr2[j]){
        i++;

    }else {
        result.add(arr1[i]);
        i++;
        j++;
    }
    }
    System.out.println(result);
1
Mahesh Naik

Essaye ça:

public static void main(String[] args) {
    int[] arr1 = new int[]{1, 2, 3, 4, 5};
    int[] arr2 = new int[]{3, 2, 5, 9, 11};
    getIntersection(arr1, arr2);
}

public static Object[] getIntersection(int[] arr1, int[] arr2) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < arr1.length; i++) {
        for (int j = 0; j < arr2.length; j++) {
            if (arr1[i] == arr2[j]) {
                list.add(arr1[i]);
            }
        }
    }
    return list.toArray();
}
1

si les tableaux sont triés

    int a1[]=new int[] {1,2,3,5,7,8};
    int a2[]=new int [] {1,5,6,7,8,9};

     // get the length of both the array
    int n1=a1.length;
    int n2=a2.length;

 //create a new array to store the intersection
   int a3[]=new int[n1];

     //run the loop and find the intersection
    int i=0,j=0,k=0;
    while(i<n1&& j<n2) {
        if(a1[i]<a2[j]) {
         // a1 element at i are smaller than a2 element at j so increment  i
            i++;
        }else if(a1[i]>a2[j]) {
         // a2 element at i are smaller than a2 element at j so increment  j

            j++;
        }else {
             // intersection element store the value and increment i, j, k    to find the next element
            a3[k]=a1[i];
            i++;
            j++;
            k++;
        }
    }


    for(int l=0;l<a3.length;l++) {
        System.out.println(a3[l]);
    }
0
Sonia Jain

Si vous avez toujours voulu implémenter cela en python, c’est un moyen de trouver une intersection.

#find intersection
def find_intersec(list_a, list_b): 
    return set(list_a).intersection(list_b) 

#since lists are kind of like arrays in python we use two lists
list_a = [ 4, 9, 1, 17, 11, 26, 28, 10,28, 26, 66, 91] 
list_b = [9, 9, 74, 21, 45, 11, 63,10] 
print(find_intersec(list_a, list_b)) 
0
grepit

Comment trouver l'intersection de 3 tableaux non triés en Java: -

J'ai utilisé l'approche Core Java utilisant des boucles for et utilisant Arrays.copyOf pour y parvenir.

public class Intersection {
    public void intersection3Arrays(int ar1[], int ar2[], int ar3[]) {
            Arrays. sort(ar1);
            Arrays. sort(ar2);
            Arrays. sort(ar3);

            int ar1Len = ar1.length;
            int ar2Len = ar2.length;
            int ar3Len = ar3.length;

            int larArray = ar3Len > (ar1Len > ar2Len ? ar1Len : ar2Len) ? ar3Len : ((ar1Len > ar2Len) ? ar1Len : ar2Len);
            System.out.println("The largest array is " +larArray);
            int[] inputArray1 = Arrays.copyOf(ar1, larArray);
            int[] inputArray2 = Arrays.copyOf(ar2, larArray);
            int[] inputArray3 = Arrays.copyOf(ar3, larArray);

            Integer[] inputArray11 = new Integer[inputArray1.length];
            Integer[] inputArray22 = new Integer[inputArray2.length];
            Integer[] inputArray33 = new Integer[inputArray3.length];

            for (int i = 0; i < inputArray11.length; i++) {
                if (inputArray11[i] == null){
                    inputArray1[i] = 0;
                }
            }
            for (int i = 0; i < inputArray22.length; i++) {
                if (inputArray22[i] == null){
                    inputArray1[i] = 0;
                }
            }
            for (int i = 0; i < inputArray33.length; i++) {
                if (inputArray33[i] == null){
                    inputArray1[i] = 0;
                }
            }

            for (int i = 0; i < inputArray11.length; i++)
                for (int j = 0; j < inputArray22.length; j++)
                    for (int k = 0; k < inputArray33.length; j++)
                    if (inputArray11[i] == inputArray22[j] && inputArray11[i] == inputArray33[k]) {
                        System.out.print(inputArray11[i]+" ");
                    }
        } 
    public static void main(String[] args) {
        Intersection3Arrays arrays = new Intersection3Arrays();
        int ar1[] = { 1, 2, 5, 10, 20, 40, 80 };
        int ar2[] = { 80, 100, 6, 2, 7, 20 };
        int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}; 
        arrays.intersection3Arrays(ar1, ar2, ar3);
    }
}
0
Kapil Sharma
if the arrays are not sorted


    int a1[]=new int[] {1,2,3,5,7,8};
    int a2[]=new int [] {1,5,6,7,8,9};
 // sort both the array
     Arrays.sort(a1);
     Arrays.sort(a2);
     // get the length of both the array
    int n1=a1.length;
    int n2=a2.length;

 //create a new array to store the intersection
   int a3[]=new int[n1];

     //run the loop and find the intersection
    int i=0,j=0,k=0;
    while(i<n1&& j<n2) {
        if(a1[i]<a2[j]) {
         // a1 element at i are smaller than a2 element at j so increment  i
            i++;
        }else if(a1[i]>a2[j]) {
         // a2 element at i are smaller than a2 element at j so increment  j

            j++;
        }else {
             // intersection element store the value and increment i, j, k    to find the next element
            a3[k]=a1[i];
            i++;
            j++;
            k++;
        }
    }


    for(int l=0;l<a3.length;l++) {
        System.out.println(a3[l]);
    }
0
Sonia Jain

trouver une intersection inclut les doublons en utilisant la carte de hachage. 

Sortie: 1 2 2 15 9 7 12

public static void main(String[] args) {
    int[] arr1 = {1, 2, 2, 1, 5, 9, 15, 9, 7, 7, 12};
    int[] arr2 = {1, 2, 2, 3, 4, 15, 9, 7, 12, 14};
    printIntersect(arr1, arr2);
}

private static void printIntersect(int[] arr1, int[] arr2) {
    Map<Integer, Integer> map = new HashMap<>();
    //put first array to map
    for (int i = 0; i < arr1.length; i++) {
        if (!map.containsKey(arr1[i])) {
            map.put(arr1[i], 1);
        } else {
            map.put(arr1[i], map.get(arr1[i]) + 1);
        }
    }

    //check all value in array two
    for (int i = 0; i < arr2.length; i++) {
        //if exist and value>1  then decrement value
        //if value is 1 remove from map
        if (map.containsKey(arr2[i])) {
            System.out.print(arr2[i] + " ");
            if (map.get(arr2[i]) > 1) {
                map.put(arr2[i], map.get(arr2[i]) - 1);
            } else {
                map.remove(arr2[i]);
            }
        }
    }
}
0
ikarayel