Winner selection script

in contest •  2 years ago  (edited)

I just wrote a short and easy PHP script to select a random winner from all the upvoters because I quickly found out that tossing a die (dice?) isn't the best method. See the script below:

$participants = ['a', 'b', 'c', 'd', 'e', 'f'];
        
$results = [];
for ($i=0; $i<10000; $i++) {
    $max = count($participants) - 1;
    $key = mt_rand(0, $max);
    if (isset($results[$participants[$key]])) {
        $results[$participants[$key]] += 1;
    } else {
        $results[$participants[$key]] = 1;
    }
}
        
foreach ($results as $participant => $hits) {
    echo "{$participant} scored {$hits} hits<br/>";
}

It's a very simple script, really, that takes the following steps:

  1. First, we start out with an array of participants, for this example there are 6 participants and they have the letters a through f
  2. We iterate 10.000 times
  3. On each iteration we pick a random participant using the mt_rand function
  4. All the hits are stored in an array and printed in the end

The output for this example script looks as follows:

d scored 1678 hits
f scored 1725 hits
e scored 1585 hits
b scored 1670 hits
a scored 1641 hits
c scored 1701 hits

So we can clearly see that the winner is participant f with 1725 hits.

Please let me know if something is unclear or if I'm doing something wrong ;)

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Pretty neat and a good solution. Like the website as well.
Will be fun to see the 5th Day. Lot of participants.

Thank you :)

how to see that script

By reading the post?

okay, thank