end0tknr's kipple - 新web写経開発

http://d.hatena.ne.jp/end0tknr/ から移転します

Math::Combinatorics で 階乗、組み合わせ、順列を算出

http://search.cpan.org/perldoc?Math::Combinatorics
書こうと思えば、書けますが、こういうmoduleがあると、やはり使ってしまいます。

#!/usr/local/bin/perl
use strict;
use Math::Combinatorics;
use Data::Dumper;

main();

sub main {
    #階乗
    my $ret_factorial = factorial(4);	# = 4x3x2x1
    print "#### FACTORIAL\n";
    print "$ret_factorial\n";

    #組み合わせ nCr = n! / ((n-r)!r!)
    my @pre_combine = qw/1 2 3/;
    my @ret_combine = combine(2,@pre_combine);	#C(3,2)
    print "#### COMBINE\n";
    print Dumper(\@ret_combine);

    #順列 nPr = = n! / (n-r)!
    my @pre_permute = qw/1 2 3/;
    my @ret_permute_1 = permute(@pre_permute);	#P(3,3)
    print "#### PERMUTE 1\n";
    print Dumper(\@ret_permute_1);

    my @ret_permute_2;
    for my $pre_permute_2 ( combine(2,@pre_permute) ){
	my @tmp = permute(@$pre_permute_2);	#P(3,2)
	push(@ret_permute_2,@tmp);
    }
    print "#### PERMUTE 2\n";
    print Dumper(\@ret_permute_2);
}

実行結果 (改行は編集しているので実際の表示とやや異なります)

[endo@colinux tmp]$ ./foo.pl 
#### FACTORIAL
24
#### COMBINE
$VAR1 = [
          ['1','2'],
          ['1','3'],
          ['2','3']
        ];
#### PERMUTE 1
$VAR1 = [
          ['1','3','2'],
          ['1','2','3'],
          ['3','1','2'],
          ['3','2','1'],
          ['2','1','3'],
          ['2','3','1']
        ];
#### PERMUTE 2
$VAR1 = [
          ['1','2'],
          ['2','1'],
          ['2','3'],
          ['3','2'],
          ['3','1'],
          ['1','3']
        ];