Reputation: 47
I have to create a method, that returns an array with common elements from two different arrays. I am aware there are lots of questions about this, but mine is a little bit different from those as I have to create a new array.
I've tried to first count how many common elements there are from two arrays, and then create an array with size the number of that.
After, I tried to set the new array to the common elements using a for loop.
public static int [] commonElements(int []a, int [] b){
int count=0;
for(int i=0;i<a.length;i++) {
for(int j=0;j<b.length;j++) {
if(a[i] == b[j]) {
count++;
}
}
}
int []array= new int[count];
for(int i=0;i<a.length;i++) {
for(int j=0;j<b.length;j++) {
if(a[i] == b[j]) {
for (int k=0; k<count; k++){
array[k]=a[i];
}
}
}
}
return array;
}
This returns four -1's, so it doesn't work. I am also required not to use arraylist, so I have no idea how to make this code complete. The expected value with
// checking common elements
System.out.println ("\nLooking for common elements in the arrays ");
int [] arr3= {56, -21, -5, 7, 10, 21, 2, -1};
int [] arr4= {-1, -56, 5, 21, 3 , 7, 4, -6, 2, 90};
int [] result4 = commonElements(arr3, arr4);
System.out.println (Arrays.toString(arr3));
System.out.println (Arrays.toString(arr4));
System.out.print ("\nCommon elements array: ");
System.out.println (Arrays.toString(result4));
in the main is
Looking for common elements in the arrays
[56, -21, -5, 7, 10, 21, 2, -1]
[-1, -56, 5, 21, 3, 7, 4, -6, 2, 90]
Common elements array: [7, 21, 2, -1]
Any help would be greatly appreciated!
Upvotes: 1
Views: 2530
Reputation: 201447
First, instead of int []array= new array[count];
you need new int[count];
- second, instead of a third inner loop when populating your output keep a position index and increment it when you encounter a duplicate. Like,
public static int[] commonElements(int[] a, int[] b) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
count++;
}
}
}
int[] array = new int[count];
int p = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
array[p] = a[i];
p++;
}
}
}
return array;
}
Alternatively, if using Java 8+, the above can be simplified by filtering on an IntStream
of the two arrays. Like,
return Arrays.stream(a).filter(i -> Arrays.stream(b).anyMatch(x -> x == i))
.toArray();
Upvotes: 0
Reputation: 521249
You might want to use a list to store the intermediate intersecting values, and then convert to an array at the end of the method:
public static int[] commonElements(int[] a, int[] b) {
List<Integer> common = new ArrayList<>();
for (int i=0; i < a.length; i++) {
for(int j=0; j < b.length; j++) {
if (a[i] == b[j]) {
common.add(a[i]);
}
}
}
int[] array = common.stream().mapToInt(Integer::intValue).toArray();
return array;
}
If you don't want to record duplicates, then replace common
with Set<Integer>
.
Upvotes: 1