Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: biased random number picking

by RichardK (Parson)
on Jul 12, 2012 at 10:31 UTC ( #981355=note: print w/replies, xml ) Need Help??

in reply to biased random number picking

Or maybe just

my @values = (100..200); my $i = int( rand(@values) ); my $j = $i; $j = int( rand(@values) ) while $i == $j;

Replies are listed 'Best First'.
Re^2: biased random number picking
by Lotus1 (Curate) on Jul 12, 2012 at 14:47 UTC

    Since rand takes an expression as its argument and there are 101 elements in @values your code is equivalent to

    my $i = int( rand(101) );

      That's correct :)

      rand returns a value less than the expression so will return an index in the range 0..100. Which is just what we needed -- woot!

        I found your solution confusing since your array had 101 elements and so wouldn't work with the op's data. I realize now this was just a test array of junk values. Your solution works fine for your array of 101 elements since both indexes will be in the range 0..100. Putting the array inside the rand() function is a general solution in case the array size changes.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://981355]
and the fire pops...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2018-06-23 15:56 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.