perl实现元素排列组合算法

网上搜了半天,没找到写的较好的利用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

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值