in reply to RE: Randomly Choose an Element from an Array
in thread Randomly Choose an Element from an Array

Here is something more complicated:

The first function (randl) generates a random number according to the logarithmic scale; it "favors" smaller numbers. The BiasedChooseFrom function picks an element; but it favors the smaller numbers.
sub randl{ return int( -$_[1] * log( $_[0] * rand() ) ); } sub BiasedChooseFrom{ return $_[ int( randl(4,int($#_/2)) ) ]; }

Replies are listed 'Best First'.
RE: RE: RE: Randomly Choose an Element from an Array
by merlyn (Sage) on Aug 27, 2000 at 19:18 UTC
    Your code continues to scare me. What's with the int functions when subscripting already forces an integer? And why do you continue to use $n * rand() when rand($n) does the same thing? And are you sure your randl function always returns a value within the range of the array subscripts? I think it can return negative numbers at first glance, which would then access the ending array elements overly often.

    In short, thanks for wanting to contribute, but please get a little more Perl experience under your belt, so we don't have to steer others away from your code. If you want, please preview your post by emailing it to me, and I'll be happy to provide you with suggestions.

    -- Randal L. Schwartz, Perl hacker