On Jan 24, 2004, at 5:31 PM, Charles Lu wrote:

Hi

If I want to randomly generate a dice (4 side) roll, I can use the following expression:

$roll = 1 + int( rand(4));

This assumes that every side of this dice has equal chance of being rolled (0.25). Thats easy. Now What if I say, that the probability of rolling a 3 is 70% and the probability of rolling a 1 or 2 or 4 is 10%.

i.e.
$probability = {  '1' => 0.1,
                      '2' => 0.1,
                      '3' => 0.7,
                      '4 => 0.1
                    }

Notice the total probability still addes up to 1. So If I want to roll this "loaded" dice, how should I modify the above code to accurately reflect the different weight of this new dice? Any suggestion would be appreciated. Thanks.

How about something like this:


sub roll_loaded_die {
        my $roll = rand;
        if ($roll <= .1) { return 1; }
        elsif ($roll <= .2) { return 2; }
        elsif ($roll <= .3) { return 4; }
        else { return 3; }
}

Hope that helps.

James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to