andrsnn - 11 months ago 71

Java Question

I have already read a few other stack overflow threads on this:

to find the intersection of two multisets in java

Best way to find an intersection between two arrays?

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

I am trying to examine two arrays as well as their number of elements (numElementsInX and numElementsInY), and return a new array which contains the common values of array x and y. Their 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}

I've read I need to use the LCS algorithm. Can anyone give me an example as to how to do this? Both the array and values in array are initialized and generated in another method, then passed into intersection.

Any help/clarification is appreciated.

Thanks!

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{

}

}

}

Answer

The simplest solution would be to use sets, as long as you don't care that the elements in the result will have a different order, and that duplicates will be removed. The input arrays `array1`

and `array2`

are the `Integer[]`

subarrays of the given `int[]`

arrays corresponding to the number of elements that you intend to process:

```
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()]);
```

The above will return an `Integer[]`

, if needed it's simple to copy and convert its contents into an `int[]`

.