Conor606
Conor606

Reputation: 107

Finding intersection

I have to find the intersection between two Set objects.

Upvotes: 2

Views: 87

Answers (2)

Bon
Bon

Reputation: 3103

You are on the right track: using a nested loop to do an exhaustive search (although it could be simplified using java collection), only some minor issues:

1) you didn't define toArray() method for your class, so assume you meant parSet.numbers when you call parSet.toArray()

2) the counter intCount needs to be outside of the loop to avoid being set to 0 in every iteration.

So the correct version should be:

public int[] intersection(Set parSet) {
    int[] interArr = new int[numbers.length];
    int[] testArr = parSet.numbers; //you didn't define toArray() for the class Set
    int intCount = 0; // move this variable out of the loop
    for (int index = 0; index < numbers.length; index++) {
        for (int compareInt = 0; compareInt < testArr.length; compareInt++) {
            if (numbers[index] == testArr[compareInt]) {
                interArr[intCount] = testArr[compareInt];
                intCount++;
            }//end if
        }//end inner for
    }//end outter for

    return interArr;
}//end method intersection

Upvotes: 1

Codor
Codor

Reputation: 17605

The variable intCount is local in the innermost if-condition, which means that only the first entry of interArr is accessed. Rearrange the implementation as follows.

public int[] intersection(Set parSet)
{
    int[] interArr = new int[numbers.length];
    int[] testArr = parSet.toArray();

    int intCount = 0; // initialization out of the loop

    for(int index = 0; index < numbers.length; index++)
    {
        for(int compareInt = 0; compareInt < testArr.length; compareInt++)
        {
            if(numbers[index] == testArr[compareInt])
            {
                interArr[intCount] = testArr[compareInt];
                intCount++;
            }//end if
        }//end inner for
    }//end outter for

    return interArr;
}//end method intersection

Upvotes: 3

Related Questions