Jump to content

Random Numbers With Percentages


DevilishLime

Recommended Posts

Hello there,

 

I was wondering if it would be possible if I could create a random number through rand();. However I want it to be able to have certain numbers have a higher percentage of being picked. Such as the number 10 would have a 20% of being picked, and the number 2 would have a 3% chance of being picked.

 

How would I go about doing this? Any help would be appreciated.

Link to comment
Share on other sites

Alternately,

 

<?php

$values = array(
// Number => Weighted chance
1 => 1,
2 => 1,
3 => 5, // 5x more likely than 1,2
4 => 3  // 3x more likely than 1,2
);

// The total of all the chances
$total = array_sum($values);
// Will track the sum of all tested chances
$i = 0;
// The number we're looking to find
$find = mt_rand(1,$total);
// Loop through value=>chance array
foreach( $values as $val => $chance ) {
// Add current chance to the running total
$i += $chance;
// Check if the running total equals or exceeds the number we're trying to find
if( $find <= $i )
// If so, break out of the loop
break;
}
// The last assigned value before breaking will contain the number
echo $val;

?>

 

The process is more complex, but the input is more simplified.

Link to comment
Share on other sites

Thank you both for the reply. I think I will have to take xyph's route, as it looks easier for the use I am wanting it for. However I will need to take some time out to learn the different functions used within the xyph's answer...so I can fully understand it.

 

Much appreciated. :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.