Chinaunix

标题: 本人Perl写的有关排列的算法_permutation [打印本页]

作者: tlqtangok    时间: 2014-05-23 15:22
标题: 本人Perl写的有关排列的算法_permutation
本帖最后由 tlqtangok 于 2014-05-23 16:02 编辑

排列组合,是一系列的问题,很多书本上都有提及。本代码是原创作品,转载请写明转自tlqtangok 的ChinaUnix
希望大家不吝拍砖,讨论切磋,以挖掘一下最好的算法。
“stdout>>


876541203
876541230
876541302
876541320
876542013
876542031
876542103
876542130
876542301
876542310
876543012
876543021
876543102
876543120
876543201
876543210
:::
:::

> cat _perl.PL

#---souce code ---
###-Usage-:  perl _perl.PL 2>/dev/null ###
#!perl
use feature qw(say);
### CONFIG AREA ###
my $MAX = 8;   # permutation num ;
####### END #######
my @a=qw();
my $len_a=$MAX*2-1;
my $file_header='
#!perl
use feature qw(say);
#--- TEST ---
my $loc_i=0;
my $MAX='."$MAX".'; # the num you want to make the
my @arr_loc=qw();
#---start permutation
';
my $for_header='for(@arr_loc[$loc_i]=0;@arr_loc[$loc_i]<$MAX; @arr_loc[$loc_i]++){      next if $arr_loc[$loc_i] ~~ @arr_loc[0..$loc_i-1];       $loc_i++;       #---;
'x ($MAX-1);
my $say_kernel='     for(@arr_loc[$loc_i]=0;@arr_loc[$loc_i]<$MAX; @arr_loc[$loc_i]++){ next if $arr_loc[$loc_i] ~~ @arr_loc[0..$loc_i-1]; say @arr_loc ;  }#end
' ;
my $for_tail='$loc_i--;      }    #end for
' x ($MAX-1) ;

open FP, '>', "bak.perl.PL";
select FP;
say "$file_header","$for_header\n","$say_kernel\n","$for_tail";
close FP;
select STDOUT;
my @perl_cml=qw(perl bak.perl.PL);
open STDERR, ">",'/dev/null';
system(@perl_cml);
close STDERR;
`rm bak.perl.PL`;

#---END source code ---
本算法是基于一个简单的原理:
for(i=0;i<MAX;i++){
for( j=0;j<MAX;j++){
j !=i;
   for(k=0;k<MAX;k++){
k!=j; k!=i;
then ...
...
}
}
}

这个算法之所以敢贴出来,是因为它的可配置(可以任意设置排列数的个数);
如果你也有这类“珍宝”,拿出来秀一下吧?! 





作者: xiumu2280    时间: 2014-05-23 15:26
看不到,又舍不得分怎么办···
作者: tlqtangok    时间: 2014-05-23 15:29
OK,我还是公开算了!我想知道大家对于排列有没有兴趣?回复 2# xiumu2280


   
作者: tlqtangok    时间: 2014-05-23 16:01
不知道大家有没有针对排列的好一点的实现? 




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2