枚举Mathematica中的所有分区

Yar*_*tov 6 wolfram-mathematica

喜欢Select[Tuples[Range[0, n], d], Total[#] == n &],但速度更快?

更新

以下是3个解决方案及其时间图,IntegerPartitions后跟Permutations似乎是最快的.分别为递归,FrobeniusSolve和IntegerPartition解决方案的时间分别为1,7和0.03

partition[n_, 1] := {{n}};
partition[n_, d_] := 
  Flatten[Table[
    Map[Join[{k}, #] &, partition[n - k, d - 1]], {k, 0, n}], 1];
f[n_, d_, 1] := partition[n, d];
f[n_, d_, 2] := FrobeniusSolve[Array[1 &, d], n];
f[n_, d_, 3] := 
  Flatten[Permutations /@ IntegerPartitions[n, {d}, Range[0, n]], 1];
times = Table[First[Log[Timing[f[n, 8, i]]]], {i, 1, 3}, {n, 3, 8}];
Needs["PlotLegends`"];
ListLinePlot[times, PlotRange -> All, 
 PlotLegend -> {"Recursive", "Frobenius", "IntegerPartitions"}]
Exp /@ times[[All, 6]]

And*_*lan 7

你的功能:

In[21]:= g[n_, d_] := Select[Tuples[Range[0, n], d], Total[#] == n &]

In[22]:= Timing[g[15, 4];]

Out[22]= {0.219, Null}
Run Code Online (Sandbox Code Playgroud)

试试FrobeniusSolve:

In[23]:= f[n_, d_] := FrobeniusSolve[ConstantArray[1, d], n]

In[24]:= Timing[f[15, 4];]

Out[24]= {0.031, Null}
Run Code Online (Sandbox Code Playgroud)

结果是一样的:

In[25]:= f[15, 4] == g[15, 4]

Out[25]= True
Run Code Online (Sandbox Code Playgroud)

您可以使用IntegerPartition更快地完成它,但是您没有以相同的顺序获得结果:

In[43]:= h[n_, d_] := 
 Flatten[Permutations /@ IntegerPartitions[n, {d}, Range[0, n]], 1]
Run Code Online (Sandbox Code Playgroud)

排序结果相同:

In[46]:= Sort[h[15, 4]] == Sort[f[15, 4]]

Out[46]= True
Run Code Online (Sandbox Code Playgroud)

它快得多:

In[59]:= {Timing[h[15, 4];], Timing[h[23, 5];]}

Out[59]= {{0., Null}, {0., Null}}
Run Code Online (Sandbox Code Playgroud)

感谢phadej的快速回答,让我再次看起来.

注意,如果你真的想要所有不同排序的排列,你只需要调用Permutations(和Flatten),即如果你想要的话

In[60]:= h[3, 2]

Out[60]= {{3, 0}, {0, 3}, {2, 1}, {1, 2}}
Run Code Online (Sandbox Code Playgroud)

代替

In[60]:= etc[3, 2]

Out[60]= {{3, 0}, {2, 1}}
Run Code Online (Sandbox Code Playgroud)


pha*_*dej 5

partition[n_, 1] := {{n}}
partition[n_, d_] := Flatten[ Table[ Map[Join[{k}, #] &, partition[n - k, d - 1]], {k, 0, n}], 1]
Run Code Online (Sandbox Code Playgroud)

这比FrobeniusSolve更快:)

编辑:如果用Haskell编写,它可能更清楚发生了什么 - 功能性:

partition n 1 = [[n]]
partition n d = concat $ map outer [0..n]
  where outer k = map (k:) $ partition (n-k) (d-1)
Run Code Online (Sandbox Code Playgroud)