-1

I want to select a number randomly, but based on probability from a group of numbers; for example (2-6).

I'd like the following distribution:

  • 6's probability should be 10%
  • 5's probability should be 40%
  • 4's probability should be 35%
  • 3's probability should be 5%
  • 2's probability should be 5%
edi9999
  • 18,115
  • 12
  • 85
  • 125
user2340767
  • 467
  • 1
  • 6
  • 10

3 Answers3

5

This is very easy to do. Watch for the comments in the code below.

$priorities = array(
    6=> 10,
    5=> 40,
    4=> 35,
    3=> 5,
    2=> 5
);

# you put each of the values N times, based on N being the probability
# each occurrence of the number in the array is a chance it will get picked up
# same is with lotteries
$numbers = array();
foreach($priorities as $k=>$v){
    for($i=0; $i<$v; $i++)  
        $numbers[] = $k;
}

# then you just pick a random value from the array
# the more occurrences, the more chances, and the occurrences are based on "priority"
$entry = $numbers[array_rand($numbers)];
echo "x: ".$entry;
Silviu-Marian
  • 10,105
  • 5
  • 45
  • 71
3

Create a number between 1 and 100.

If      it's <= 10       -> 6
Else if it's <= 10+40    -> 5
Else if it's <= 10+40+35 -> 4

And so on...

Note: your probabilities don't add up to 100%.

Karoly Horvath
  • 91,854
  • 11
  • 113
  • 173
2

The best you can do is generate a number between 0 and 100, and see in what range the number is:

$num=rand(0,100);

if ($num<10+40+35+5+5) 
    $result=2;

if ($num<10+40+35+5)
    $result=3;

if ($num<10+40+35)
    $result=4;

if ($num<10+40)
    $result=5;

if ($num<10)
    $result=6;

Be careful, your total probability isn't equal to 1, so sometimes $result is undefined

See @grigore-turbodisel 's answer if you want something that you can configure easily.

edi9999
  • 18,115
  • 12
  • 85
  • 125