简体   繁体   中英

PHP Logic - How to handle score ties?

I'm trying to distribute prizes based on scores. I'm having trouble with my logic when it comes to TIE's . Can anyone give me logic pointers on handling a tie between 3 or more people?

UPDATE: The Goal is this --

  1. Make an ARRAY of the people who have tied (Only them)
  2. Know what POSITION those people are in.

I have a few sample phases you can skim through:

Example 1 - Works with 0 Ties

<?php
function give_prize($a, $b) {return;}

$prize = array(500, 250, 75);

$user = array(
    'user1' => 650,
    'user2' => 500,
    'user3' => 200,
    'user4' => 100,
);

$prize_count = count($prize);

for ($i = 0; $i < $prize_count; $i++) {
    give_prize($user[$i], $prize[$i]);
}

Example 2 - Works with 1 Tie (Is it a good way?)

<?php   
for ($i = 0; $i < $prize_count; $i++) {

    if (isset($user[$i+1])) {
        if ($user[$i] == $user[$i++]) {
            // My Tie breaker code
        }
    }
}

But what would I do in a tie of 3 or 4 people? Should I follow the above and do more if checks?

I would start by grouping users by score and then sorting those groups in descending order. Once that is complete it will be easier to assign prizes no matter what rules you have.

$usersByScore = array();
foreach ($user as $name => $score) {
    $usersByScore[$score][] = $name;
}
krsort($usersByScore);

For example, this turns the input $user

$user = array(
    'user1' => 500,
    'user2' => 400,
    'user3' => 750,
    'user4' => 500,
);

into $usersByScore :

$usersByScore = array(
    750 => array('user3'),
    500 => array('user1', 'user4'),
    400 => array('user2'),
);

Now you can issue prizes however you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM