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

421 views Asked by At

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.

2

There are 2 answers

0
Don't Panic On BEST ANSWER

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;
}
2
Manav On

Something like this?

    $points = 10;
    $a = 0;
    $b = 0;
    $c = 0;
    $d = 0;
    for($i=0; $i<$points; $i++) {
        $rand = rand(1,4);
        if($rand == 1) {
            $a++;
        } else if ($rand == 2) {
            $b++;
        } else if ($rand == 3) {
            $c++;
        } else if ($rand == 4) {
            $d++;
        }
    }