I have already read a few other stack overflow threads on this:
to find the intersection of two multisets in java
How do I get the intersection between two arrays as a new array?
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.
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{ } } }
Create two sets called union and intersection. To find the union, add the first array's elements to the set union. Now, add all the second array elements if they are not present in the set union. To find the intersection, find the common elements and add them to the set.
The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order.
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[]
.
If you are fine with java-8, then the simplest solution I can think of is using streams and filter. An implementation is as follows:
public static int[] intersection(int[] a, int[] b) { return Arrays.stream(a) .distinct() .filter(x -> Arrays.stream(b).anyMatch(y -> y == x)) .toArray(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With