使用 Perl 生成组合
我需要编写一个 Perl 例程来生成给定集合的 n 选择 k 组合。我不需要数有多少套,我必须能够将它们打印出来。我很困惑。
任何建议表示赞赏。
问候。
I need to write a Perl routine that will generate the n choose k combinations of a given set. I don't need to count how many sets there are, I have to be able to print them out. I'm pretty stumped.
Any advice is appreciated.
Regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个名为 Math::Combinatorics 的模块,它可以生成任意组合 (nCr)、排列 (nPr) 和排列您提供给它的一组东西。
There's a module called Math::Combinatorics that produces combinations (nCr), permutations (nPr), and derangements of any set of things that you provide to it.
如果您想要不重复的组合,您可以生成长度为 k 的所有二进制数,选择具有 n 1 的二进制数并将它们以固定顺序应用到集合中:0 表示未选中,1 表示已选中。要获取二进制数,请使用
sprintf '%05b'
;要计算 1,请使用tr/1//
。If you want combinations without repetition, you can generate all binary numbers to length k, select those that have n 1's and apply them to the set in a fixed order: 0 means not selected, 1 means selected. To get a binary number, use
sprintf '%05b'
; to count 1's usetr/1//
.