3

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?

UpAndAdam
  • 4,300
  • 2
  • 26
  • 43
user962449
  • 3,565
  • 9
  • 37
  • 52
  • 2
    Create an array and put the names*weigth into it. So for example james 1 time, Sam 3 times. Then you can pick a random element. – clentfort Jun 01 '12 at 22:30

3 Answers3

3

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.

Community
  • 1
  • 1
Jeroen
  • 12,789
  • 4
  • 40
  • 61
1

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

Glen Swinfield
  • 628
  • 4
  • 8
1

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.

Baobabs
  • 31
  • 3