网上搜了半天,没找到写的较好的利用perl实现元素排列组合的算法,自己写了一个,请大家拍砖。
注:该方法实现的是无冗余的排列组合,例如 a b 和 b a 只保留a b一个,每种可能的组合结果都是以一个数组的形式保存的,方便后期对变量组合数据进行进一步的处理。这个排列组合是个二维数组。
1. 下面是我写的perl实现元素排列组合算法:
#!/usr/bin/perl
#use strict;#use warnings;
my @list=("a","b","c","d");
my @list_combine=&get_combine(\@list);
for (my $i=0;$i<@list_combine;$i++) {
my @temp=@{$list_combine[$i]};
print "$i\t@temp\n";
}
print "\n";
sub get_combine {my $list=shift;
my @list=@{$list};
my @list_new=();
foreach my $list (@list) {
my @temp=($list);
push (@list_new,[@temp]);
}
my @list_new2=();
my $list_new_index=0;
for (my $cycle=0;$cycle<@list;$cycle++) {
for (my $i=$list_new_index;$i<@list_new;$i++) {
my @temp=@{$list_new[$i]};
for (my $j=0;$j<@list;$j++) {
my $flag=0;
for (my $k=0;$k<@temp;$k++) {
my $index=&get_index(\@list,$temp[$k]);
if ($temp[$k] eq $list[$j]) {
$flag=1;
}elsif ($index>=$j) {
$flag=1;
}
}
next if ($flag==1);
my @temp2=(@temp,$list[$j]);
push (@list_new2,[@temp2]);
}
}
$list_new_index=$#list_new+1;
push (@list_new,@list_new2);
@list_new2=();
}
return @list_new;
}
sub get_index {
my $list=shift;
my @list=@{$list};
my $element=shift;
my $index;
for (my $i=0;$i<@list;$i++) {
if ($list[$i] eq $element) {
$index=$i;
last;
}
}
return $index;
}
2. 输出结果如下所示:
0 a
1 b
2 c
3 d
4 a b
5 a c
6 a d
7 b c
8 b d
9 c d
10 a b c
11 a b d
12 a c d
13 b c d
14 a b c d