2017-10-23 3 views
0

私はこの機能を700の整数のように大量に使用したいが、その機能は実行に時間がかかる。誰かがパフォーマンスを向上させるアイディアを持っていますか?複合Javaの性能

public static Set<Set<Integer>> combinations(List<Integer> groupSize, int k) { 

    Set<Set<Integer>> allCombos = new HashSet<Set<Integer>>(); 
    // base cases for recursion 
    if (k == 0) { 
     // There is only one combination of size 0, the empty team. 
     allCombos.add(new HashSet<Integer>()); 
     return allCombos; 
    } 
    if (k > groupSize.size()) { 
     // There can be no teams with size larger than the group size, 
     // so return allCombos without putting any teams in it. 
     return allCombos; 
    } 

    // Create a copy of the group with one item removed. 
    List<Integer> groupWithoutX = new ArrayList<Integer> (groupSize); 
    Integer x = groupWithoutX.remove(groupWithoutX.size() - 1); 

    Set<Set<Integer>> combosWithoutX = combinations(groupWithoutX, k); 
    Set<Set<Integer>> combosWithX = combinations(groupWithoutX, k - 1); 
    for (Set<Integer> combo : combosWithX) { 
     combo.add(x); 
    } 
    allCombos.addAll(combosWithoutX); 
    allCombos.addAll(combosWithX); 
    return allCombos; 
} 
+0

"n!"よりも速い時間にすべての組み合わせを取得することはできません –

+0

ブレークポイントを設定してステップを破り、実行するには長すぎる? (ストップウォッチを使用して) –

+0

私はJavaで簡単な解決策を見ていません(Scalaは多くを助けるでしょう)。興味深い記事があります:https://stackoverflow.com/questions/3515739/parallel-programming-with-recursive-functions – marco

答えて

0

:)ありがとうございその他のデータ構造。Set<Integer>の代わりにBitSetを試すことができます。整数値にワイルド範囲(負の値、大きなギャップ)がある場合は、groupSizeのインデックスを使用します。

整数値の代わりにインデックスを使用することは他の利点があります。ビットとしてのすべてのサブセットはforループで実行できます(BigIntegerが設定されています)。

データなし。または、すべての組み合わせのイテレータ(ストリーム)を繰り返し処理メソッドに適用します。

同時実行性。 パラレルステートメントは、4/8の係数を意味します。 ThreadPoolExecutor and Futureかもしれません。


アルゴリズムを最適化すること自体

セットのセットは、より良いリストである可能性があります。それはセットの追加を大幅に向上させます。 そして、アルゴリズムが誤って同じセットを作成しないかどうかを示します。

-1

Setのどのような機能あなたが返された値に使用する必要がありますするつもりですか?

Parallel.For(combosWithX, new Parallel.Operation<Set<Integer>, Void>() { 

     @Override 
     public Void perform(Set<Integer> pParameter) { 
      pParameter.add(x); 
      return null; 
     } 

     //break loop if false 
     @Override 
     public boolean follow() { 
      return true; 
     } 

     //add result if true 
     @Override 
     public boolean result() { 
      return true; 
     } 

     //Performance if true 
     @Override 
     public boolean async() { 
      return false; 
     } 
    }); 

"Parallel.For" for Java?

+1

これはどうやって質問に答えますか? Parallel.Forとは何ですか? – Popeye

1

ではParallel.For

for (Set<Integer> combo : combosWithX) { 
    combo.add(x); 
} 

によって置き換えについて

iterator()またはcontains(...)のようなものがほんの少し必要な場合は、オンザフライで組み合わせを計算するIteratorを返すことを検討できます。

lexicographically ordered set hereのn番目の組み合わせを生成する興味深いメカニズムがあります。