0

Intersection array from two arrays, Java.

Hi, please could you look at this code, I would like to fill up an empty array of Int appending to it only the common elements from the two first arrays. I am only using java.util.Arrays library, don't want to use any lists or hashset or whatever...just plain for loops and methods for arrays of Int. Could you help me to complete the code? public class Main3 { public static void main(String[] args) { int[] arr1 = {4, 23, 17, 2}; int[] arr2 = {23, 5, 17, 1}; int count=0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr2.length; j++) { if (list[i] == list1[j]) { count++; int[] common = new int[count]; for (int k = 0; k < common.length; k++) { common[k] = list[i]; } } } } } of course the result is not that I was expecting...:( please help, thanks!

20th Dec 2018, 7:51 AM
Roberto
4 Respuestas
+ 1
The code is modified. (https://code.sololearn.com/cvi3k6mqfm12/#java) Check again. I used a temp array before adding in common.
20th Dec 2018, 8:56 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 1
Many thanks Prokopios!
20th Dec 2018, 9:15 AM
Roberto
0
There are some errors in your code 1. for (int i = 0; i < arr.length; i++) { ===> for (int i = 0; i < arr1.length; i++) { 2. if (list[i] == list1[j]) { ==> if (arr1[i] == arr2[j]) { 3. common[k] = list[i]; ==> common[k] = arr1[i]; 4. Add one more } at the end Nevertheless the problem still exists. Numbers are duplicated in the array. I believe that you want the distincts. https://code.sololearn.com/cvi3k6mqfm12/#java Keep in mind that in the above code I use 4 positions as a size of common array. but I print only the common elements.
20th Dec 2018, 8:25 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
0
Thank you, I watched your code, but the output I was having in mind is an array, not single elements printed out. Output should be something like: common[] = {23, 17} I was thinking of somehting like: System.out.println(Arrays.toString(common[l])); but it doesn't work even if I import java.util.Arrays :((
20th Dec 2018, 8:37 AM
Roberto