0

Java で 2 つのセットの結合と交差を見つける関数を書いてきましたが、アルゴリズムのどこかに問題があるようです。たとえば、次の 2 つの数値ベクトルを入力すると、次のようになります。

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

私は以下を受け取ります:

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

これは明らかに間違っています。私は受け取っているはずです:

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

交差点/ユニオンに関連するメインのコードは次のとおりです。

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

ここで、Inty は、Integer クラスでは不可能な、ベクトルに格納する必要がある整数の値を変更できるように作成したクラスです。ここに私が書いた関数があります:

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

なぜこれが機能しないのかについて誰かが洞察を与えることができれば、私はそれを聞きたいです. 前もって感謝します!

4

1 に答える 1

1

メソッドisDuplicatedはパラメーターiを使用しません! 実際には常にTrueを返すと思います。関数のコード全体を次のように置き換える

return p2Shingles.contains(i)

十分なはずです。

于 2014-08-05T22:20:30.543 に答える