perl實現元素排列組合演算法

2021-08-21 05:00:42 字數 1325 閱讀 4699

網上搜了半天,沒找到寫的較好的利用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++) ;

print "$i\t@temp\n";

}print "\n";

sub get_combine ;

my @list_new=();

foreach my $list (@list)

my @list_new2=();

my $list_new_index=0;

for (my $cycle=0;$cycle<@list;$cycle++) ;

for (my $j=0;$j<@list;$j++) elsif ($index>=$j)

}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 $element=shift;

my $index;

for (my $i=0;$i<@list;$i++)

}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

排列組合演算法實現

全排列表示把集合中元素的所有按照一定的順序排列起來,使用p n,n n 表示n個元素全排列的個數。例如 的全排列為 123 132 213 231 312 321 共6個,即3!321 6。這個是怎麼算出來的呢?首先取乙個元素,例如取出了1,那麼就還剩下。然後再從剩下的集合中取出乙個元素,例如取出2...

排列組合演算法

在開發的過程中很難免會到排列組合,剛開始通過for迴圈來搞定。但是對於工作了近五年的我而已,不能像 新人那樣做了。如果所要組合的集合大於40,你不可能寫40個for迴圈吧!這裡使用了數學的演算法,到底是啥演算法,高人也沒說!不過我把它的思想提公升了一下。如下 ifndef combination h...

排列組合演算法

1.排列演算法 include define max num 100 void print int n,int num void swap int a,int b int arrange int i,int n,int num i return count int combination int u...