Random Number PHP Confusion

475 views Asked by At

So lets say I have 2 numbers in decimals (eg .75 and .25). I am trying to make a function that gets these 2 numbers and chooses a "winner" randomly but based on those 2 numbers' percentages. In short terms, I need the .75 number to have a better chance at getting picked then the .25 number (the .25 can still get picked, but it has only a 25% chance). How should I go about doing this?

4

There are 4 answers

0
shmeeps On BEST ANSWER
$var1 = 25;
$var2 = 75;
$total = $var1 + $var2;

$rand = mt_rand(1, $total);

if($rand <= $var1)
    echo("Value one ({$var1}) Wins!");
else
    echo("Value two ({$var2}) Wins!");

Something like that should work.

0
zerkms On
$prob = array(25, 75);

$total = array_sum($prob);

$rand = mt_rand(1, $total);

var_dump($rand);

foreach ($prob as $i => $p) {
    $rand -= $p;

    if ($rand <= 0) {
        $winner = $i;
        break;
    }
}

var_dump($winner);
0
mario On

In this simplistic case you could use:

 if (rand(0,1000)/1000 <= 0.25)
 {
     $winner = $first;   // 25% number
 }
 else {
     $winner = $second;  // 75% number
 }
0
Patrick Fisher On

If they don't always add up to 1, this will still work:

$winner = ( (rand(0,1000) / 1000) <= ($first / ($first + $second)) ) ? $first : $second;