in reply to New Jersey Lottery Probability

Recursion anyone?
#!/usr/bin/perl use strict; my $probability = permutation(50, 5); print $probability * 36; sub permutation { my $number = shift; my $count = shift || return 1; return $number * permutation($number-1,$count-1); }
Or to do my best at obfuscation ... the ever popular one liner:
sub permutation { return $_[1] ? $_[0] * permutation($_[0]-1,$_[1]-1) : 1; }
Useless, but fun anyway.

Replies are listed 'Best First'.
RE: Re: New Jersey Lottery Probability
by chromatic (Archbishop) on May 04, 2000 at 04:47 UTC
    No need for recursion, here's my obfuscation:
    sub permutation { my ($prob, $start) = (1, shift); $prob *= $start-- foreach (1 .. $_[0]); $prob; }
    Another approach that requires thinking a bit backwards:
    sub permutation { my $prob = 1; $prob *= $_ foreach ((($_[0]+1) - $_[1]) .. $_[0]); return $prob; }
    Even shorter and harder on the eyes:
    sub permutation { my $prob = 1; return (map { $prob *= $_ } (($_[0] - $_[1] + 1) .. $_[0]))[-1]; }
    I stand by the first I posted, though. Anyone who can get this down to a single statement gets my respect.
      You can make the last one even more useless..
      sub p { return (map { $a ? ($a *= $_) : ($a = 1) } (($_[0] - $_[1] + 1) .. + $_[0]))[-1]; }
      The little ?: operator is great for making code unreadable :)

      For those of you who are not familiar with ?: it is the 'conditional operator' and can be found in the perlop pages.
      I like the last one, map is alway a good one to whip out. I bet it is the fastest one also.

      Of course it is true that recursion is not needed. It rarely is needed. And this was a simple loop, so in a normal application: use a simple loop, not recursion. I did it because I felt like being a smart-ass :) I would not recommend using recursion where you did not absolutely have to.

      Also recursion can be slower, nearly impossible to debug, and all around confusing ... but that is why it is fun for academic exercises!

      For 'real' code I would go with your code or btrott's slimmed down version.

      Just though I would clarify for users that arent hip on recursion