Remove all duplicates from two given int arrays (no list)

I'm stuck at a task. Maybe someone can help me? I'm given two integer arrays of unknown length like Array 1 = {1, 4, 7, 3} and Array 2 = {1, 7}. I have to return a third Array containing only the integers which are only in one of the arrays. So in this case, Array 3 would be {4, 3}. I've tried something like this:

public static void main(String[] args) {
  int [] range = {2, 3, 4, 5, 6, 7};
  int [] excludedValues = {1, 4, 6};
  int [] exclusionRange = new int [range.length - excludedValues.length + 1];

  for (int i = 0; i < range.length ; i++) {
      if (range[i] != Arrays.binarySearch(excludedValues, range[i])) {
          exclusionRange[i] = range[i];
      }
  }

    System.out.println(Arrays.toString(exclusionRange)); // Should return {2, 3, 5, 7}
}

But it (obviously) doesn't work at all.

Here you can see a detailed description of the content which should be returned:

enter image description here

Thanks for your help in advance :)


Solution 1:

I would simply use the built in Java functions of Lists.

public static void main(String[] args)
{
    int[] range = { 2, 3, 4, 5, 6, 7 };
    int[] excludedValues = { 1, 4, 6 };
    
    List<Integer> list = Arrays.stream(range).boxed().collect(Collectors.toList());
    List<Integer> listE = Arrays.stream(excludedValues).boxed().collect(Collectors.toList());
    list.removeAll(listE);

    int[] exclusionRange = new int[list.size()];
    for (int i = 0; i < list.size(); i++)
        exclusionRange[i] = (int) list.get(i);

    System.out.println(Arrays.toString(exclusionRange));
}

Solution 2:

According to the picture you linked, i believe you want something like this

import java.util.Arrays;

public class MyClass {
    public static int[] createRangeWithExclusions(int rangeStartInclusive,int rangeEndInclusive,int[] excludedValues){
       int sz = rangeEndInclusive - rangeStartInclusive  + 1;
       
       for(int exclude : excludedValues){
            if(exclude >= rangeStartInclusive && exclude <= rangeEndInclusive){
                sz--;
            }
        }
       
       
       int []ret = new int[sz];
       
       int idx = 0;
       for(int i = rangeStartInclusive; i <= rangeEndInclusive; i++){
           boolean include = true;
           for(int exclude : excludedValues){
               if(i == exclude){
                   include = false;
                   break;
               }
           }
           
           if(include){
               ret[idx] = i;
               idx++;
           }
       }
       
       return ret;
    }
    
    public static void main(String args[]) {
      int[] exlusions = {1,4,6};
      int [] resp = createRangeWithExclusions(2, 7, exlusions);

      System.out.println(Arrays.toString(resp));
    }
}