in reply to Re: New Jersey Lottery Probability
in thread New Jersey Lottery Probability

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.

Replies are listed 'Best First'.
RE: RE: Re: New Jersey Lottery Probability
by perlmonkey (Hermit) on May 04, 2000 at 11:34 UTC
    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.
RE: RE: Re: New Jersey Lottery Probability
by perlmonkey (Hermit) on May 04, 2000 at 05:55 UTC
    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