#/usr/bin/env perl6
use v6.c;
sub postfix:<!>(Int $n) is tighter(&infix:</>) {
factorial( $n )
}
multi sub factorial( Int $n where $n > 0 ) {
[*] 1..$n
}
multi sub factorial( Int $n where $n == 0 ) {
1
}
multi sub combin(@n where @n.elems > 0, Int $r where $r < @n.elems) {
@n.elems! /( $r! * ( @n.elems - $r )! )
}
multi sub combin(@n where @n.elems > 0, Int $r where $r == @n.elems) {
return 1
}
multi sub permu(@n where @n.elems > 0, Int $r where $r < @n.elems --> Int:D) {
Int( @n.elems! / (@n.elems - $r )! )
}
multi sub permu(@n where @n.elems > 0, Bool :$a! --> Int:D) {
Int( @n.elems! / [*] @n.Bag.grep({ $_.value !== 1 }).map({ $_.value! }) ) ;
}
multi sub binomial_coefficient(@n, @t, Int :$exponet! where $exponet == 0 --> Real:D) {
1
}
multi sub binomial_coefficient(@n, @t, Int :$exponet!
where { [&&] (
@n.elems == @t.elems == 2,
@t »<=» $exponet,
$exponet > 0,
|@n »~~» Real,
|@t »~~» Int) }
--> Real:D) {
my $k = $exponet - @t[0];
combin(^$exponet, $k) * ( @n[0] ** @t[0] ) * ( @n[1] ** @t[1] )
}
multi sub multinomial_coefficient(@n, @t, Int :$exponet! where $exponet == 0 --> Real:D) {
1
}
multi sub multinomial_coefficient(@n, @t, Int :$exponet!
where { [&&] (
@n.elems == @t.elems > 2,
@t »<=» $exponet,
$exponet > 0,
|@n »~~» Real,
|@t »~~» Int) }
--> Real:D) {
$exponet! / ( [*] @t»! )
* ( [*] ( @n Z** @t ) )
}
my $ans1 = combin(^10, 6);
my $ans2 = permu('TALLAHASSEE'.comb.grep({$_ ne 'A'})):a
* combin( ^('TALLAHASSEE'.comb.grep({$_ ne 'A'}).elems + 1),
'TALLAHASSEE'.comb.grep('A').elems);
my $ans3 = binomial_coefficient((1,2), (2,5), :exponet(7));
my $ans4 = multinomial_coefficient((2,3,4), (2,5,3), :exponet(6) );
say qq:to/EOF/;
EX:
c(10, 6) = ?
sol: {$ans1}
EX:
TALLAHASSEE 這些安排方法中有 A不相鄰多少種
sol: {$ans2}
EX:
A: (x + 2y)⁷ => x²y⁵ 的係數為
B: (2x + 3y + 4z)⁶ => x²y⁵z³
sol:
A = {$ans3}
B = {$ans4}
EOF