在Perl中,我怎么能生成一个列表的所有可能的组合? [英] In Perl, how can I generate all possible combinations of a list?
本文介绍了在Perl中,我怎么能生成一个列表的所有可能的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有列表的文件,并需要使各线到另一个比较的文件。例如,我的文件中有这样的:
AAA
BBB
CCC
DDD
EEE
我想最终名单看起来是这样的:
<为pre> AAA BBBAAA CCC
AAA DDD
AAA EEE
BBB CCC
BBB DDD
BBB EEE
CCC DDD
CCC EEE
DDD EEE
我试图做到这一点在Perl,对于这个第一次和我有一个小麻烦。我知道你需要一个数组,然后把它分解,但在那之后我有一些麻烦。
解决方案
使用算法::组合学 。迭代器为基础的方法是preferable在一次产生的一切。
#!的/ usr / bin中/ perl的包膜使用严格的;使用警告;
使用算法::组合学QW(组合);我的琴弦$ = [QW(AAA BBB CCC DDD EEE)];我的$ = ITER组合($字符串,2);而(我的$ C = $ iter-&gt;接下来){
打印@ $ C的\\ n;
}
输出:
AAA BBB
AAA CCC
AAA DDD
AAA EEE
BBB CCC
BBB DDD
BBB EEE
CCC DDD
CCC EEE
DDD EEE
I have a file with a list, and a need to make a file that compares each line to the other. for example, my file has this:
AAA BBB CCC DDD EEE
I would like the final list to look like this:
AAA BBB AAA CCC AAA DDD AAA EEE BBB CCC BBB DDD BBB EEE CCC DDD CCC EEE DDD EEE
I am trying to do this in Perl, for this first time and am having a little trouble. I do know that you need to make an array, and then split it, but after that I am having some trouble.
解决方案
Use Algorithm::Combinatorics. The iterator based approach is preferable to generating everything at once.
#!/usr/bin/env perl
use strict; use warnings;
use Algorithm::Combinatorics qw(combinations);
my $strings = [qw(AAA BBB CCC DDD EEE)];
my $iter = combinations($strings, 2);
while (my $c = $iter->next) {
print "@$c\n";
}
Output:
AAA BBB AAA CCC AAA DDD AAA EEE BBB CCC BBB DDD BBB EEE CCC DDD CCC EEE DDD EEE
这篇关于在Perl中,我怎么能生成一个列表的所有可能的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文