Wolfram mathematica 枚举Mathematica中的所有分区
像Wolfram mathematica 枚举Mathematica中的所有分区,wolfram-mathematica,Wolfram Mathematica,像选择[Tuples[Range[0,n],d],Total[#]==n&],但是更快 更新 下面是3种解决方案及其时间图,整数分割后的排列似乎最快。递归解、FrobeniusSolve解和整数分割解的计时分别为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
选择[Tuples[Range[0,n],d],Total[#]==n&]
,但是更快
更新
下面是3种解决方案及其时间图,整数分割后的排列似乎最快。递归解、FrobeniusSolve解和整数分割解的计时分别为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]]
分区[n,1]:={{n};
分区[n,d]:=
压平[桌子][
映射[Join[{k},#]&,分区[n-k,d-1]],{k,0,n}],1];
f[n,d,1]:=分区[n,d];
f[n_,d_,2]:=FrobeniusSolve[Array[1&,d],n];
f[n_,d_,3]:=
展平[Permutations/@IntegerPartitions[n,{d},Range[0,n]],1];
时间=表[First[Log[Timing[f[n,8,i]]],{i,1,3},{n,3,8}];
需要[“绘图图例”];
ListLinePlot[时间,绘图范围->全部,
PlotLegend->{“递归”、“Frobenius”、“整数部分”}]
Exp/@times[[All,6]]
你的职能:
In[21]:= g[n_, d_] := Select[Tuples[Range[0, n], d], Total[#] == n &]
In[22]:= Timing[g[15, 4];]
Out[22]= {0.219, Null}
尝试:
结果是一样的:
In[25]:= f[15, 4] == g[15, 4]
Out[25]= True
In[46]:= Sort[h[15, 4]] == Sort[f[15, 4]]
Out[46]= True
您可以通过以下方法加快速度,尽管结果的顺序不同:
In[43]:= h[n_, d_] :=
Flatten[Permutations /@ IntegerPartitions[n, {d}, Range[0, n]], 1]
排序结果相同:
In[25]:= f[15, 4] == g[15, 4]
Out[25]= True
In[46]:= Sort[h[15, 4]] == Sort[f[15, 4]]
Out[46]= True
速度要快得多:
In[59]:= {Timing[h[15, 4];], Timing[h[23, 5];]}
Out[59]= {{0., Null}, {0., Null}}
感谢phadej的快速回答让我再次看到
注意,如果您确实需要所有不同顺序的排列,即如果您需要,则只需要调用(和)
In[60]:= h[3, 2]
Out[60]= {{3, 0}, {0, 3}, {2, 1}, {1, 2}}
而不是
In[60]:= etc[3, 2]
Out[60]= {{3, 0}, {2, 1}}
这比FrobeniusSolve更快:)
编辑:如果用Haskell编写,可能会更清楚发生了什么-功能性的:
partition n 1 = [[n]]
partition n d = concat $ map outer [0..n]
where outer k = map (k:) $ partition (n-k) (d-1)