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
https://forums.phpfreaks.com/topic/269270-random-numbers-with-percentages/
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.

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. :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.