How do I generate set partitions of a certain size?

纵然是瞬间 提交于 2019-12-11 05:16:49

问题


I would like to generate partitions for a set in a specific way: I need to filter out all partitions which are not of size N in the process of generating these partitions. The general solution is "Generate all “unique” subsets of a set (not a powerset)".

For the set S with the following subsets:

[a,b,c]
[a,b]
[c]
[d,e,f]
[d,f]
[e]

and the following 'unique' elements:

a, b, c, d, e, f

the result of the function/method running with the argument N = 2 should be:

[[a,b,c], [d,e,f]]

While the following partitions should be filtered out by the function/method:

[[a,b,c], [d,f], [e]]
[[a,b], [c], [d,e,f]]
[[a,b], [c], [d,f], [e]]

The underlying data structure is not important and could be arrays, sets or whatever.


Reason: I need to filter some partitions out before I have the full set of all partitions, because the function/method which generates all partitions is rather computationally intensive.


According to "Generating the Partitions of a Set", the number of possible partitions can be huge: 44152005855084346 for 23 elements. My data is 50-300 elements in the starting set, so I definitely need to filter out partitions that have size not equal to N before I save them anywhere.


回答1:


Once you have the partitions as given by Frederick Cheung that you linked, do:

partitions.select{|partition| partition.length == 2}


来源:https://stackoverflow.com/questions/8646396/how-do-i-generate-set-partitions-of-a-certain-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!