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 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]);
Find intersection of two arrays
You're already maintaining a count, idx
, of the common elements. So
there's no need to rely on a sentinel value like "0" to see which
elements were actually found in common -- you already know how many were found.
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]);
}
}
}
}
Intersection of two arrays with repetition
Please try following function:
public int[] findSameElements(int[] p1, int[] p2)
{
int count = 0;
bool[] choosen = new bool[p2.length];
for (int i = 0; i < p1.length; i++)
{
for (int j = 0; j < p2.length; j++)
{
if (!choosen[j] && p1[i] == p2[j])
{
choosen[j] = true;
count++;
break;
}
}
}
int[] result = new int[count];
count = 0;
for (int i = 0; i < p2.length; i++)
{
if (choosen[i])
{
result[count] = p2[i];
count++;
}
}
return result;
}
If necessary you also should apply sorting, this solution has O(N^2) complexity.
Also possible made O(NLogN) complexity.
Finding intersection of two sorted arrays in Java
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find()
method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
Intersection of Two Arrays getting IndexOutOfBound Error
- One problem I notice is that you are not resetting
count
inuniqueArray1
. I would set it to 0 in the beginning of the method. - You should copy the
count
values to aretArray
as follows.
double[] retArray = new double[count];
for (int i = 0; i < count; i++) {
retArray[i] = tempArray[i];
}
return retArray;
This will get rid of any lingering 0.0 values. Proper technique is that this be done in the same method to remove burden from further processing.
- In the following loop, see my comments.
// need to reset count to 0
count = 0;
// Finding Common Elements between between 2 Arrays
boolean flag = true;
for (int outerindex = 0; outerindex < resultArray1.length;
outerindex++) {
flag = true;
for (int innerindex = 0; innerindex < resultArray2.length;
innerindex++) {
if (resultArray1[outerindex] == resultArray2[innerindex]) {
flag = false;
// might as well get out of this loop since flag will never
// be true.
break;
}
}
if (flag == false) {
// important to assign to location count (at the beginning of the
// array).
intersectArray[count] = resultArray1[outerindex];
count++;
}
}
- and when printing the values, use count, not the array length.
for (int index = 0; index < count; index++) {
System.out.print(intersectArray[index] + " ,");
}
Here is the complete program. Some names have changed slightly.
import java.util.Arrays;
public class Test1 {
void findIntersectionOfArray(double[] array1, double[] array2) {
// get unique elements and return arrays.
double[] resultArray1 = uniqueArray1(array1); //12
double[] resultArray2 = uniqueArray1(array2);
// initialize temporary result array
double[] tempResultArray = new double[array1.length];
// Finding Common Elements between between 2 Arrays
boolean flag = true;
int count = 0;
for (int outerindex = 0; outerindex < resultArray1.length; outerindex++) {
flag = true;
for (int innerindex = 0; innerindex < resultArray2.length; innerindex++) {
if (resultArray1[outerindex] == resultArray2[innerindex]) {
flag = false;
break; // break out if false since it won't go back to true
}
}
// add element to temp result array at count location
if (flag == false) {
tempResultArray[count] = resultArray1[outerindex];
count++;
}
}
// prepare to fill final result array of size count
double[] finalResultArray = new double[count];
for (int index = 0; index < count; index++) {
finalResultArray[index] = tempResultArray[index];
}
// print the array.
System.out.println(Arrays.toString(finalResultArray));
}
// Method Unique Array will give Array1 Unique element
double[] uniqueArray1(double[] givenArray) {
int count = 0;
double[] tempArray = new double[givenArray.length]; // 6
boolean isNumberPresent = true;
for (int outerindex = 0; outerindex < givenArray.length; outerindex++) {
isNumberPresent = true;
for (int innerindex = 0; innerindex < givenArray.length; innerindex++) {
if ((givenArray[outerindex] == tempArray[innerindex])) {
isNumberPresent = false;
}
}
if (isNumberPresent) {
tempArray[count] = givenArray[outerindex];
count++;
}
}
// only copy valid array elements
double[] returnArray = new double[count];
for (int i = 0; i < count; i++) {
returnArray[i] = tempArray[i];
}
return returnArray;
}
public static void main(String[] args) {
Test1 test = new Test1();
double[] array1 = { 10.45, 14.0, 18.35, 88.88, 54.10, 18.35 };
double[] array2 = { 17.20, 13.30, 10.45, 18.35, 84.33, 13.30 };
test.findIntersectionOfArray(array1, array2);
}
}
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)
Related Topics
Background Timer Task in Jsp/Servlet Web Application
How to Add Mouselistener to Item on Java Swing Canvas
Android - How to Take Screenshot Programmatically
How to Know Whether I am in a Call on Android
How to Send Data from Dialogfragment to a Fragment
Dynamically Get Drawables by Id
Create a Bitmap/Drawable from File Path
How to Give an Imageview Click Effect Like a Button on Android
Java.Sql.Sqlexception: No Suitable Driver Found for Jdbc:Microsoft:Sqlserver
Giving Jmenuitem's Name to It's Actionlistener
How to Populate a Drop Down with a List Using Thymeleaf and Spring
Map.Clear() VS New Map:Which One Will Be Better
Android: Dex Cannot Parse Version 52 Byte Code
Android Post Picture to Facebook Wall
How to Get Current Location in Googlemap Using Fusedlocationproviderclient