3

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.

3
  • work within an array, and have a look at php.net/array_rand Commented Sep 7, 2017 at 12:51
  • Do you need to set $points to 0 at the end? Commented Sep 7, 2017 at 12:58
  • @Manav Not necessarily, but I wan to distribute all 10 points Commented Sep 7, 2017 at 13:01

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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++;
        }
    }

2 Comments

I like your answer. But if the $points is a big number, like 10000, it will have to iterate 10000 times
Ah, thats there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.