Java, find intersection of two arrays
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[]
.
How do I get the intersection between two arrays as a new array?
Since this looks to me like a string algorithm, I'll assume for a moment that its not possible to sort this sequence (hence string) then you can use Longest Common Sequence algorithm (LCS)
Assuming the input size is constant, then the problem has a complexity of O(nxm), (length of the two inputs)
Intersection between two arrays
I think following code helps you
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Map<Integer,Integer> map1=new HashMap<Integer,Integer>();
int A[]={1 , 3 , 5 , 7 ,9 };
int B[]={1 ,3 , 4 ,5 , 6 ,7 , 10};
int i;
for(i=0;i<B.length;i++)
map1.put(B[i],1);
for(i=0;i<A.length;i++)
{
Integer v1=map1.get(A[i]);
if(v1==null)
{
System.out.println("Missing number="+A[i]);
}
}
for(i=0;i<A.length;i++)
{
Integer v1=map1.get(A[i]);
if(v1!=null)
{int val=v1;
map1.put(A[i],val+1);
// System.out.println("Missing number="+A[i]);
}
}
for(i=0;i<B.length;i++)
{
Integer v1=map1.get(B[i]);
if(v1!=null && v1<2)
{
System.out.println("Added element in B="+B[i]);
}
}
}
}
Python - return intersection of two arrays
Not sure how big your arrays will get, but if they remain fairly small, this could work:
import numpy as np
arr1 = np.array([(255, 255, 255), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
intersectedArr = []
for a1, a2 in zip(arr1, arr2):
if np.array_equal(a1, a2):
intersectedArr.append(a1)
print(np.array(intersectedArr))
arr1 = np.array([(100, 100, 100), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
intersectedArr = []
for a1, a2 in zip(arr1, arr2):
if np.array_equal(a1, a2):
intersectedArr.append(a1)
print(np.array(intersectedArr))
How do I find the intersection of two arrays in Java?
This should be an easy way to do.
int a[] = {3, 10, 4, 2, 8};
int[] b = {10, 4, 12, 3, 23, 1, 8};
List<Integer> aList = Arrays.asList(a);
List<Integer> bList = Arrays.asList(b);
aList.retainAll(bList);
System.out.println(" a intersection b "+aList);
int[] c = aList.toArray(new int[0]);
Finding intersection between 2 arrays of objects with dynamic keys
if you want to compare with every index then you can do something like this
const hierarchy1 = [{
level1: 'Shoes',
level3: "xyz"
}]
const hierarchy2 = [{
level1: 'Shoes',
level2: 'Sneakers',
}, {
level3: "xyz"
}]
function intersection(arr1, arr2) {
let final = []
// loop over first array
for (let i = 0; i < arr1.length; i++) {
let element = arr1[i]
let temp = {}
// loop over all indexes of second array
for (let data of arr2) {
// check every key fro data to see if there's any intersection
Object.keys(data).forEach(key => {
if (data[key] === element[key] && key in element) {
temp[key] = element[key]
}
})
}
// if we found any intersection push it in final array
if (Object.keys(temp).length) {
final.push(temp)
}
}
return final
}
console.log(intersection(hierarchy1, hierarchy2))
Simplest code for array intersection in javascript
Use a combination of Array.prototype.filter
and Array.prototype.includes
:
const filteredArray = array1.filter(value => array2.includes(value));
For older browsers, with Array.prototype.indexOf
and without an arrow function:
var filteredArray = array1.filter(function(n) {
return array2.indexOf(n) !== -1;
});
NB! Both .includes
and .indexOf
internally compares elements in the array by using ===
, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some
instead.
How to calculate intersection of multiple arrays in JavaScript? And what does [equals: function] mean?
I wrote a helper function for this:
function intersection() {
var result = [];
var lists;
if(arguments.length === 1) {
lists = arguments[0];
} else {
lists = arguments;
}
for(var i = 0; i < lists.length; i++) {
var currentList = lists[i];
for(var y = 0; y < currentList.length; y++) {
var currentValue = currentList[y];
if(result.indexOf(currentValue) === -1) {
var existsInAll = true;
for(var x = 0; x < lists.length; x++) {
if(lists[x].indexOf(currentValue) === -1) {
existsInAll = false;
break;
}
}
if(existsInAll) {
result.push(currentValue);
}
}
}
}
return result;
}
Use it like this:
intersection(array1, array2, array3, array4); //["Lorem"]
Or like this:
intersection([array1, array2, array3, array4]); //["Lorem"]
Full code here
UPDATE 1
A slightly smaller implementation here using filter
Related Topics
Java Random Always Returns the Same Number When I Set the Seed
Effective Gif/Image Color Quantization
How to Check If a Single Character Appears in a String
How to Measure Distance and Create a Bounding Box Based on Two Latitude+Longitude Points in Java
How to Ask the Selenium-Webdriver to Wait for Few Seconds in Java
Maven Modules + Building a Single Specific Module
Handling Exceptions from Java Executorservice Tasks
What Is the Meaning of the Cascadetype.All for a @Manytoone JPA Association
Nullpointerexception in Collectors.Tomap with Null Entry Values
Classpath Resource Not Found When Running as Jar
How to Get Parameters from the Url with Jsp
Explicit Casting from Super Class to Subclass
Java List.Contains(Object with Field Value Equal to X)
Differencebetween Integer and Int in Java
Java Thread.Sleep Puts Swing UI to Sleep Too
Java Thread Garbage Collected or Not