枚举 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]]
Like Select[Tuples[Range[0, n], d], Total[#] == n &]
, but faster?
Update
Here are the 3 solutions and plot of their times, IntegerPartitions followed by Permutations seems to be fastest. Timing at 1, 7, 0.03 for recursive, FrobeniusSolve and IntegerPartition solutions respectively
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]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的函数:
尝试 FrobeniusSolve:
结果是相同的:
您可以使其更快与 IntegerPartitions,尽管您没有以相同的顺序获得结果
:排序结果是相同的:
速度更快:
感谢 phadej 的快速回答让我再次查看。
请注意,您只需要调用 Permutations (和 Flatten) 如果您实际上想要所有不同顺序的排列,即如果您想要
而不是
Your function:
Try FrobeniusSolve:
The results are the same:
You can make it faster with IntegerPartitions, though you don't get the results in the same order:
The sorted results are the same:
It is much faster:
Thanks to phadej's fast answer for making me look again.
Note you only need the call to Permutations (and Flatten) if you actually want all the differently ordered permutations, i.e. if you want
instead of
这甚至比 FrobeniusSolve 还要快:)
编辑:如果用 Haskell 编写,可能会更清楚正在发生的事情 - 功能也是如此:
This is even quicker than FrobeniusSolve :)
Edit: If written in Haskell, it's probably clearer what is happening - functional as well: