Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

binomial coefficient

by Anonymous Monk
on Jul 05, 2009 at 13:05 UTC ( #777339=obfuscated: print w/replies, xml ) Need Help??

I am out of ideas to get this smaller,but I feel it can. _ calculates it recursive and __ does a direct calculation.
sub _{($:,$,,$;)=@_;$;=$;?$;:1;($:>$,)?_($:-1,$,,$;*$:/($:-$,)):$;;} sub __{($:,$;)=@_;$;++;for($,=1;$:>$;;$:--){$,*=$:/($:-$;)}$,;};

Replies are listed 'Best First'.
Re: binomial coefficient
by Anonymous Monk on Jul 05, 2009 at 15:42 UTC
    I got it down to 49 characters:
    sub ___{ ($n,$k)=@_;$r=1;$r*=$n/($n-$k),$n--while$n>$k;$r; };
Re: binomial coefficient
by Anonymous Monk on Jul 06, 2009 at 13:18 UTC
    44 characters, changed $k,$n into $_[0] and pop, changed while to for loop. Removed semicolon a the end.
    sub bc { $r=1;$r*=$_/($_[0]-$_+1)for(1+pop..$_[0]);$r }
Re: binomial coefficient
by spx2 (Deacon) on Jul 08, 2009 at 00:27 UTC

    I liked a lot your versions , now it's time for me to write my own in Perl6 , so here it goes:

    sub bc($n,$k){[*]map ->$x, $y{$x/$y},(($k+1..$n)Z(1..$n-$k));} (this version is described)
    sub bc($n,$k){[*]map ->$x, $y{$x/$y},(($n-$k+1..$n)Z(1..$k));} (the same thing,if you simplify (n-k)! instead of k!)

    I beat the initial one(the "__" one) by 2 characters (mine is 62 characters). It's still compact code but more readable in the sense that one can identify that you're first zipping together two arrays namely the intervals $k+1 -> $n and 1 -> $n-$k which happens if you simplify the k! with the denumerator in the definition of the combinations , after that we're iterating on both intervals at the same time and we're making fractions with their elements , and after that we reduce the fractions by multiplying all of them together using this reduce meta-operator. I find that Perl6 leads to natural code.

    Thanks go to moritz_,TimToady,Limbic-Region,jnthn on #perl6 , :)

      I decided to register myself. Better late than never. About your code, it is beautiful! It is very natural indeed. I should take an in depth look into perl6 very soon.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: obfuscated [id://777339]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2020-11-26 18:29 GMT
Find Nodes?
    Voting Booth?

    No recent polls found