1

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 :)

2
  • You mean - no duplicates right ?? Commented Jan 14, 2022 at 17:24
  • What exactly are your constraints? You can only use arrays, but you are not allowed to use any other collections, correct? Commented Jan 14, 2022 at 17:48

6 Answers 6

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));
}
Sign up to request clarification or add additional context in comments.

Comments

1

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));
    }
}

1 Comment

Simple and doesn't use anything "fancy". It could break if there are duplicate values in the exclusion array.
0

If the ask is to filter common values from the given arrays, you can use Apache Commons Collections library to solve this issue, which gives a lot of utility functions. For our use-case, you can use the disjunction function.

List<Integer> list1 = Arrays.asList(1, 3, 4, 7);
List<Integer> list2 = Arrays.asList(1, 7, 2);

System.out.println(CollectionUtils.disjunction(list1, list2)); //order does not matter here

Output

[2, 3, 4]

Comments

0
public static int[] findExclusionRange(int[] range, int[] excludedValues) {
    Set<Integer> unique = Arrays.stream(excludedValues)
                                .boxed()
                                .collect(Collectors.toSet());
    return Arrays.stream(range)
                 .boxed()
                 .filter(v -> !unique.contains(v))
                 .distinct()
                 .mapToInt(i -> i)
                 .toArray();
}

Comments

0

Here's a variation of Henrique Possatto's answer, using a List<Integer> to accumulate the valid values:

  public static void main(String[] args) {
    int [] excludedValues = {-1, 1, 2, 3};
    int[] range = createRangeWithExclusions(-1, 3, excludedValues);
    System.out.println(Arrays.toString(range));
  }      

  public static int[] createRangeWithExclusions(int rangeStartInclusive, int rangeEndInclusive, int[] excludedValues) {
    // unknown number of values in resulting set, use a List and accumulate valid values
    List<Integer> lstRange = new ArrayList<Integer>();
    // iterate over the inclusive range values
    for(int i=rangeStartInclusive; i<=rangeEndInclusive; i++) {
      // examples include an array with non-sorted exclusion values, so we can't use a binary search
      // exclude values from the exclusion set
      boolean exclude = false;
      for(int x : excludedValues) {
        if (i == x) {
          exclude = true;
          break;
        }
      }    
      if (!exclude) {
        lstRange.add(i);
      }
    }

    // convert our List<Integer> to int[] and return it
    int index=0;
    int[] returnArray = new int[lstRange.size()];
    for(Integer i : lstRange) {
      returnArray[index++] = i;
    }
    return returnArray;
  }

Comments

-1

In JS we can solve the problem like this.

const fun = () => {
  let range = [2, 3, 4, 5, 6, 7];
  let excludedValues = [1, 4, 6];
  let combineArr = [...range, ...excludeValues];
  let tempObj = {}
  for (let i =0;i<combineArr.length;i++) {
      if (tempObj[combineArr[i]]) {
         delete tempObj[combineArr[i]]
      } else {
         tempObj[combineArr[i]] = 1
      }
  }
  return Object.keys(tempObj)

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

1 Comment

Why post a JavaScript solution if this is clearly a Java question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.