I want to transport one array(arr1) into another array(arr3), but don’t transport the integers that are in another array (arr2), so if a number from arr1 is not in arr 2 then put it in arr3 if it is part of arr2 skip it and don’t add it to arr3
This is what I got, but it doesn’t work I think because of the for loop for(int l=0;l<arr2.length;l )
, but I can’t find another solution that works.
int[] arr3 = new int[arr1.length - arr2.length];
for (int i = 0; i < arr1.length; i ) {
for(int l=0; l<arr2.length; l ) {
if (arr[i] != arr2[l]) {
arr3[j] = arr[i];
}
}
}
CodePudding user response:
Since your second FOR loop is not checking for all the items in the second array, it will not give you correct result.
Create a helper function which will iterate the whole array to check if a number is present in the array or not. like this
boolean containsTarget(int[] array, int target){
for(int i = 0; i < array.length; i ){
if(array[i] == target){
return true;
}
}
return false;
}
and then call this function inside your first FOR loop to perform the check.
List<Integer> arr3 = new ArrayList<Integer>(); //Using arraylist because i am not sure what will be the size of the final array.
for (int i = 0; i < arr1.length; i ) {
if(!containsTarget(arr2, arr1[i])){
arr3.add(arr1[i]);
}
}
I haven't tested this code but on a higher level this logic should work.
CodePudding user response:
you idea have some issue for loop condition. the follow code .i test
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4};
int[] test = test(arr1, arr2);
System.out.println(test);
}
private static int[] test(int[] arr1,int[] arr2){
int[] arr3 = new int[arr1.length - arr2.length];
int j=0;
for (int i = 0; i < arr1.length; i ) {
boolean flag=true;
for(int l=0; l<arr2.length; l ) {
if (arr1[i] == arr2[l]) {
flag=false;
break;
}
}
if (flag){
arr3[j] = arr1[i];
j ;
}
}
return arr3;
}
the output value {1,2,5} I guess the result which you want get .