在N個元素的數組中獲取K個元素的所有組合問題
阿新 • • 發佈:2018-04-19
.cn int 腳本 count erl sin cal 獲取 結果 print "combinations of 2 from: ".join(" ",@n)."\n";
print "------------------------".("--" x scalar(@n))."\n";
while(my @combo = $combinat->next_combination){
print join(‘ ‘, @combo)."\n";
}
print "\n";
print "display the permutations: ".join(" ",@n)."\n";
print "------------------------".("--" x scalar(@n))."\n";
while(my @permu = $combinat->next_permutation){
print join(‘ ‘, @permu)."\n";
}
可以寫循環,也可以用模塊。
百度許久找到一個博客 http://blog.sina.com.cn/s/blog_4a0824490101f1kc.html 詳細介紹了Algorithm::Combinatorics
受此啟發,又找到了 Math::Combinatorics
由於前面的博客介紹了Algorithm::Combinatorics,所以本博客介紹一下Math::Combinatorics
perl 腳本
use Math::Combinatorics;
my @n = qw(a b c);
my $combinat = Math::Combinatorics->new(count => 2,data => [@n]);
print "------------------------".("--" x scalar(@n))."\n";
while(my @combo = $combinat->next_combination){
print join(‘ ‘, @combo)."\n";
}
print "\n";
print "display the permutations: ".join(" ",@n)."\n";
print "------------------------".("--" x scalar(@n))."\n";
print join(‘ ‘, @permu)."\n";
}
結果
combinations of 2 from: a b c
------------------------------
a b
a c
b c
display the permutations: a b c
------------------------------
a b c
a c b
b a c
b c a
c a b
c b a
在N個元素的數組中獲取K個元素的所有組合問題