user962449
user962449

Reputation: 3873

how to choose a number based on weight

let's say I have an object:

$person->name = array('James',
                      'Sam',
                      'Kevin',
                      'Mike');
$person->weight = array(1,
                        3,
                        1,
                        7);

In the above example James has a weight of 1, Sam has a weight of 3, etc. (based on index location)

I want to be able to echo only one person's name. The higher the weight, the greater the chance of your name being selected. The lower the weight, the lower your chance is for your name to be selected. Sort of like a lottery, but with weights. Any idea on how to do this?

Upvotes: 3

Views: 391

Answers (3)

Jeroen
Jeroen

Reputation: 13257

This should work:

$weighted = array();
foreach($person->weight as $key => $value) {
    $weighted = array_merge($weighted, array_fill(0, $value, $key));
}
$index = array_rand($weighted);
echo $person->name[$index];

Based on this answer.

Upvotes: 3

Baobabs
Baobabs

Reputation: 31

You could also sum up all the weights and generate a random number between one and that sum. Then you could iterate over the array of weights summing them up until the result is >= the random number and take that person. Might be slightly faster.

Upvotes: 1

Glen Swinfield
Glen Swinfield

Reputation: 638

Create a new array, Add the name Sam to the array 3 times, mike 7 times, the others once and pick one at random.

Upvotes: 1

Related Questions