-1

I am having trouble figuring out the algorithm that will find the differences between two integer arrays. I already have a sorting method that it will be ran through so the numbers are in ascending order.

For example:

SetX = { 1, 2, 3, 4, 5 }

SetY = { 0, 2, 4, 6 }

The return should be the numbers in SetX that does not appear in SetY.

so resultSet = { 1, 3, 5 }

Sometimes I get the correct answer if I do small arrays but if I do arrays that are 4 or more Integers long it gives me the wrong return.

Can someone look over my code and tell me what I am doing wrong?

public static int firstFruit(int[] setX, int usedSizeSetX, int[] setY, int usedSizeSet2, int[] resultSet) {
    int a = 0, b = 0, c = 0;

    while( a < usedSizeSetX && b < usedSizeSetY){
        if(setX[a] == setY[b]) {
            a++;
        } else if(setX[a] == setY[b]){
            b++;
        } else {
            resultSet[c++] = setX[a++];
            b++;
        }
    }
    return c;
}
Pableto
  • 3
  • 3
  • Can you give some example inputs where it is giving the wrong answer? – BretC Dec 06 '16 at 16:26
  • 5
    your first two checks are exactly the same. You'll never get into the second conditional... – jgitter Dec 06 '16 at 16:27
  • [Here](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html) there is a list of all the methods the class **Array** offers. For each element in one array you could use binsearch to find if it appears in the other array. –  Dec 06 '16 at 16:29
  • apache common lib has `CollectionUtils.disjunction()` – Kent Dec 06 '16 at 16:30
  • What is the logic behind your algorithm? I notice that you check for the same condition twice .. in `if` and in `else if` (`setX[a] == setY[b]`) .. this doesn't make sense .. may be a typo? – PKey Dec 06 '16 at 16:34

1 Answers1

1

I think your conditionals are a little FUBAR. The processing should be:

  1. If setX[a] > setY[b] -> b++
  2. If setX[a] < setY[b] -> a++
  3. Else -> add setX[a] to the result, a++, b++
jgitter
  • 3,396
  • 1
  • 19
  • 26
  • could you explain it in layman's terms please. I think the multiple counters are confusing me. – Pableto Dec 06 '16 at 16:46
  • @Pableto I'd suggest taking the example arrays you give and walking through it yourself. It can be useful to write out every step on a piece of paper. – AndyReifman Dec 06 '16 at 18:05