在 Perl 中,如何生成列表的所有可能组合? [英] In Perl, how can I generate all possible combinations of a list?
本文介绍了在 Perl 中,如何生成列表的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有列表的文件,并且需要制作一个将每一行与另一行进行比较的文件.例如,我的文件有这个:
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
我第一次尝试在 Perl 中执行此操作,但遇到了一些麻烦.我知道你需要创建一个数组,然后拆分它,但之后我遇到了一些麻烦.
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.
推荐答案
使用 Algorithm::Combinatorics一>.基于迭代器的方法比一次性生成所有内容更可取.
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";
}
输出:
AAA BBB
AAA CCC
AAA DDD
AAA EEE
BBB CCC
BBB DDD
BBB EEE
CCC DDD
CCC EEE
DDD EEE
这篇关于在 Perl 中,如何生成列表的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文