在perl中从列表生成无序对
我是新手 我想从一个单词列表中循环一对单词:在perl中从列表生成无序对,perl,Perl,我是新手 我想从一个单词列表中循环一对单词: @words = ("word1", "word2", "word3", "word4"); 我想创建和处理所有成对的单词,但成对排序并不重要,即成对 (“word1”、“word2”)和(“word2”、“word1”)被认为是相同的,只应生成其中一个 有没有一种简单的方法可以做到这一点?显而易见的解决方案是有一个嵌套循环,类似于: for my $i1 (0 ... $#words) { for my $i2 ($i1 + 1 ...
@words = ("word1", "word2", "word3", "word4");
我想创建和处理所有成对的单词,但成对排序并不重要,即成对
(“word1”、“word2”)
和(“word2”、“word1”)
被认为是相同的,只应生成其中一个
有没有一种简单的方法可以做到这一点?显而易见的解决方案是有一个嵌套循环,类似于:
for my $i1 (0 ... $#words) {
for my $i2 ($i1 + 1 ... $#words) {
process_pair(words[$i1], words[$i2])
}
}
但是我正在寻找比这更像Perl的东西。提前感谢。对于固定的R=2,您提供的解决方案非常合适
for my $i1 (0 ... $#words) {
for my $i2 ($i1 + 1 ... $#words) {
process_pair($words[$i1], $words[$i2])
}
}
但是如果R更大或者是可变的呢?你可以使用NestedLoops
做一些功能强大的事情
use Algorithm::Loops qw( NestedLoops );
my $R = 2;
NestedLoops(
[ [ 0..$#words ],
( sub { [$_+1..$#words] } ) x ($R-1),
],
\&process_pair,
);
或者作为迭代器
use Algorithm::Loops qw( NestedLoops );
my $R = 2;
my $iter = NestedLoops([
[ 0..$#words ],
( sub { [$_+1..$#words] } ) x ($R-1),
]);
while (my @combo = $iter->()) {
process_pair(@combo);
}
但这很难理解。专门解决这个问题的解决方案将是最干净的
use Math::Combinatorics qw( );
my $R = 2;
my $iter = Math::Combinatorics->new( count => $R, data => \@words );
while (my @combo = $iter->next_combination) {
process_pair(@combo);
}
哇,我不知道算法有这样的方法。非常好!