Search code examples
javasetset-intersectionset-union

Incorrect Calculation of Union and Intersection of Sets in Java


I've been writing functions that find the union and intersection of two sets in Java, but I appear to have a problem in my algorithm somewhere. For example, when I feed in the following two vectors of numbers:

A = {0, 1, 3, 4, 5}
B = {1, 1, 2, 3, 4, 5, 6, 7, 8}

I receive the following:

Union = {1, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {0, 1, 3, 4, 5}

Which is clearly incorrect. I should be receiving:

Union = {0, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {1, 3, 4, 5}

Here's the code in my main pertaining to the intersection/union:

    Vector<Inty> p1Shingles = new Vector<Inty>();
    p1Shingles.add(new Inty(0));
    p1Shingles.add(new Inty(1));
    p1Shingles.add(new Inty(3));
    p1Shingles.add(new Inty(4));
    p1Shingles.add(new Inty(5));

    Vector<Inty> p2Shingles = new Vector<Inty>();
    p2Shingles.add(new Inty(1));
    p2Shingles.add(new Inty(1));
    p2Shingles.add(new Inty(2));
    p2Shingles.add(new Inty(3));
    p2Shingles.add(new Inty(4));
    p2Shingles.add(new Inty(5));
    p2Shingles.add(new Inty(6));
    p2Shingles.add(new Inty(7));
    p2Shingles.add(new Inty(8));        

    Vector<Inty> shinglesUnion = vectorUnion(p1Shingles, p2Shingles);
    Vector<Inty> shinglesIntersection = vectorIntersection(p1Shingles, p2Shingles);

Here, Inty is a class I created so that I can change the values of the integers I need to store in a vector, which is not possible with the Integer class. Here are the functions I've written:

private static <T> Vector<T> vectorIntersection(Vector<T> p1Shingles, Vector<T> p2Shingles)
{
    Vector<T> intersection = new Vector<T>();

    for(T i : p1Shingles)
    {
        if(p2Shingles.contains(i))
        {
            intersection.add(i);
        }
    }

    return intersection;
}

private static <T> Vector<T> vectorUnion(Vector<T> p1Shingles, Vector<T> p2Shingles) {
    Vector<T> union = new Vector<T>();

    union.addAll(p2Shingles);

    for(T i : p1Shingles)
    {
        if(!p2Shingles.contains(i))
        {
            union.add(i);
        }
    }

    return union;
}

If anyone could give any insight as to why this is not working, I'd love to hear it. Thanks in advance!


Solution

  • The method isDuplicated does not use parameter i! Actually I think it always returns True. Replacing the entire code of the function by

    return p2Shingles.contains(i)
    

    should be enough.