質問

きのようにPythonの yieldMathematica, 創出のために発電機?参照例 こちらの のために、コンセプトです。

更新 この例のように対して繰り返し処理を実行するすべての組み合、 O(n) スペース:(アルゴリズムとしてSedgewickのアルゴリズムの書籍):

gen[f_, n_] := Module[{id = -1, val = Table[Null, {n}], visit},
  visit[k_] := Module[{t},
    id++; If[k != 0, val[[k]] = id];
    If[id == n, f[val]];
    Do[If[val[[t]] == Null, visit[t]], {t, 1, n}];
    id--; val[[k]] = Null;];
  visit[0];
  ]

そのように:

gen[Print,3], 印刷すべての6組の長さ3.

役に立ちましたか?

解決

以前の記述は、 Compile またより速くコードです。アルゴリズムを利用から fxtbook, 以下のコードを生成する次の仕切りの際の字句順:

PermutationIterator[f_, n_Integer?Positive, nextFunc_] := 
 Module[{this = Range[n]},
  While[this =!= {-1}, f[this]; this = nextFunc[n, this]];]

次のコードを想定した実行バージョン8:

ClearAll[cfNextPartition];
cfNextPartition[target : "MVM" | "C"] := 
  cfNextPartition[target] = 
   Compile[{{n, _Integer}, {this, _Integer, 1}},
    Module[{i = n, j = n, ni, next = this, r, s},
     While[Part[next, --i] > Part[next, i + 1], 
      If[i == 1, i = 0; Break[]]];
     If[i == 0, {-1}, ni = Part[next, i]; 
      While[ni > Part[next, j], --j];
      next[[i]] = Part[next, j]; next[[j]] = ni;
      r = n; s = i + 1;
      While[r > s, ni = Part[next, r]; next[[r]] = Part[next, s]; 
       next[[s]] = ni; --r; ++s];
      next
      ]], RuntimeOptions -> "Speed", CompilationTarget -> target
    ];

その

In[75]:= Reap[PermutationIterator[Sow, 4, cfNextPartition["C"]]][[2, 
   1]] === Permutations[Range[4]]

Out[75]= True

このことはより良い性能の gen 機能です。

In[83]:= gen[dummy, 9] // Timing

Out[83]= {26.067, Null}

In[84]:= PermutationIterator[dummy, 9, cfNextPartition["C"]] // Timing

Out[84]= {1.03, Null}

Mathematicaの仮想マシンが遅い:

In[85]:= PermutationIterator[dummy, 9, 
  cfNextPartition["MVM"]] // Timing

Out[85]= {1.154, Null}

もちろんのころの近くのCコードの実施なり大幅な高速化を純でトップレベルのコードです。

他のヒント

おそらく意味の問題をより一般的なものの例を繰り返し処理を行順列で与えられているページへのリンクがされておりMathematica:

Scan[Print, Permutations[{1, 2, 3}]]

Print があり、差し替えが可能と機能です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top