Distributing a prize evenly within a lottery system
Whats the best way to distribute a number evenly across "three people?" for instance let's say I have 300 of something each person gets 100 but then if I have 2 of something then the first two people 开发者_开发百科get 1 while the third person is out of luck. What would be the quickest way to do this? Sometimes that 300 number will be as high as 2,000,000 and I'm not really sure if a for() loop is the best solution for this?
If your prize fund is made up of P
indivisible units and you have W
winners, then each winner will get:
P / W
units.
After you have disbursed these, you will have
P % W
units left. If this is zero, you're done. If this is P
it means you have more winners than you have prizes. You'll have to decided on the course of action there yourself... simplest solution would be to draw
P - W
from some slush fund stored for such occasions.
If the remainder is something other than 0 or P
, then you have to decide yourself on what the fairest thing to do is... maybe start a slush fund....
EDIT
Following comments, such that you avoid a slush fund:
my @winners = get_list_of_winners(); # Sorted randomly or in some 'fair' order
my $base_prize = P / W; # P and W defined as above
my $leftovers = P % W;
for my $i (0 .. $#winners) {
$winners[$i] = $base_prizel + ( ($i < $leftovers)?1:0 );
}
I'm assuming that you mean that you want to distribute remaining pieces evenly among the three people.
First I would divide 2,000,000 by 3 and round down. (We'll call this x)
Then would take 2,000,000 %(mod) 3 and find that result. (We'll call this y)
Then I would create an array the size of the number of people you have.
Set each element to x then generate y random numbers between 0 and x-1 and add one to each of these indexes
Like so:
<?php
$items = 2000000;
$winners = 3;
$x = floor($items / $winners);
$y = $item % $winners;
$distribution = $array();
$distribution = array_fill(0, $winners, $x);
for($i = 0; $i < $y; $i++)
{
$distribution[rand(0, $winners - 1)]++;
}
?>
Now you have an array with the same number of elements as people and each is filled with a number of items recieved. It may not be even but it is fair and random.
Just use integer-based math. If you only have two prizes to give away and three people to win, nobody wins anything. If you have anything left over such that your number of prizes is not evenly divisible by the number of winners, then you just have things left over. There is no fair way to do this, it's basic math.
精彩评论