Search code examples
phpmathprobability-distribution

PHP: How to distribute values to variables with equal probability?


Note to moderators: This is not a homework assignment.

I have the following example:

$points = 10;
$a = 0;
$b = 0;
$c = 0;
$d = 0;

I want to randomly distribute the points to the variables ($a,$b,$c,$d) until $points reach zero. So, expected random output after running some function/script should look like this:

$points = 0;// Must be zero
$a = 3;
$b = 1;
$c = 0;
$d = 6;

I'm thinking of doing a simple solution, which is the following:

while($points > 0) {
    $points_taken = mt_rand(0, $points);
    $points -= $points_taken;
    $a += $points_taken;

    $points_taken = mt_rand(0, $points);
    $points -= $points_taken;
    $b += $points_taken;

    $points_taken = mt_rand(0, $points);
    $points -= $points_taken;
    $c += $points_taken;

    $points_taken = mt_rand(0, $points);
    $points -= $points_taken;
    $d += $points_taken;
}

The function has 1 problem: $a has much more higher chance of taking more points (or even all points) because it's first in the list, while $d has much more higher chance of taking less points (or no points at all) because it's last in the list.

Question: How can I give all variables equal chance of distribution?

Note: It's fine if one of the variables took all the points.


Solution

  • You can use randomly select one of the variables from a range, and assign to it using a variable variable.

    $vars = range('a','d');
    while ($points) {
        $points_taken = mt_rand(0, $points);
        $points -= $points_taken;
        ${$vars[mt_rand(0, 3)]} += $points_taken;
    }