Random Number PHP Confusion
So lets say I have 2 numbers in decimals (eg .75 and .25). I am t开发者_JAVA技巧rying 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?
$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);
If they don't always add up to 1, this will still work:
$winner = ( (rand(0,1000) / 1000) <= ($first / ($first + $second)) ) ? $first : $second;
$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.
In this simplistic case you could use:
if (rand(0,1000)/1000 <= 0.25)
{
$winner = $first; // 25% number
}
else {
$winner = $second; // 75% number
}
精彩评论