-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
  • 19,701
  • 13
  • 88
  • 127
user2340767
  • 527
  • 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,565
  • 6
  • 50
  • 72
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
  • 94,607
  • 11
  • 117
  • 176
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) {
    $result = 6;    
} elseif ($num < 50) { // 10 + 40
    $result = 5;
} elseif ($num < 85) { // 10 + 40 + 35
    $result = 4;
} elseif ($num < 90) { // 10 + 40 + 35 + 5
    $result = 3;
} else {
    $result = 2;
}

Be careful, if your total probability isn't equal to 1, then sometimes $result will be undefined.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
edi9999
  • 19,701
  • 13
  • 88
  • 127