JREAM
JREAM

Reputation: 5941

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?

Upvotes: 1

Views: 396

Answers (1)

David Harkness
David Harkness

Reputation: 36552

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.

Upvotes: 6

Related Questions