Quick actions

cmd+k|ctrl+k

Navigation

Languages

Subfactorial user-defined operator symbol

Snippet info

Language

Raku

Visibility

public

Author

richardsantiago0101

Created

2019-05-21T12:03:18Z

Updated

2019-05-21T13:36:47Z

# Factorial user-defined operator symbol: n!
sub postfix:<!>(UInt $parameter --> UInt) is tighter(&infix:<**>){
    return [*] 1..$parameter;
};
# Subfactorial user-defined operator symbol: !n
# Defined as `multi` since prefix `!` is also defined as the boolean negation operator
multi sub prefix:<!>(UInt $parameter) is tighter(&infix:<**>){ 
    my @terms = map {(-1)**$^x/$^x!}, 0..$parameter;
    my $sum = [+] @terms;
    return $parameter!*$sum;
};
sub combinations(UInt $elements,UInt $extraction){
    return $elements!/($extraction!*($elements-$extraction)!);
};
sub permutations(UInt $elements,UInt $extraction){
    return $extraction!*combinations($elements,$extraction);
};
say "A set of 9 distinct elements all drawn together has...{combinations(9,9)} combinations, {permutations(9,9)} permutations, and {!9} derangements!";
say 'The first twenty one derangements are:';
my $number = 0;
until $number == 21 {
    say !$number;
    $number++;
};
INFO