Reputation: 905
I am creating a game which marks the top 2 highest "scores" from each game as winners.
If two of the scores are the same, there will have to be a tiebreaker (unless the two matching scores are first and second place).
How can I (efficiently) make a function which returns these results for the following possibilities:
Possible game results for 6 different games:
$a = array(20,19,18,17,16,15); // no tie breaker needed - [1], [2] win
$b = array(20,20,18,17,16,15); // no tie breaker needed - [1], [2] win
$c = array(20,19,19,17,16,15); // tie breaker needed for [2], [3] values
$d = array(20,20,20,17,16,15); // tie breaker needed for [1], [2], [3] values
$e = array(20,19,19,19,16,15); // tie breaker needed for [2], [3], [4] values
$f = array(20,20,20,20,20,20); // tie breaker needed for all values
EDIT: THE SOLUTION:
<?php
$score = array("green"=>10, "pink"=>10, "orange"=>9, "blue"=>8, "yellow"=>7);
$count = 0;
foreach ($score as $value) {
$count++;
// if the count is 2
if ($count === 2) {
// save the value as a variable
$second = $value;
// if the count is 3
} else if ($count === 3) {
// if 2nd place and 3rd place have the same score - tiebreaker
if ($second === $value) {
// add matches to array for tiebreaker
$result = array_keys($score, $value);
// if 2nd place and 3rd place have different scores - no tiebreaker
} else {
// split first 2 places from the array
$result = array_slice($score, 0, 2);
}
}
}
?>
Upvotes: 0
Views: 2172
Reputation: 17630
My guess is that you have more than scores as part of the objects you're ranking (otherwise, does it matter "which" raw score is first?). In the comparator you're using to compare the results, you can take in to consideration any of the additional data. So, if your object really looks like this (JSON object format, not PHP. Forgive):
{
"name":"frank",
"score":20,
"class":"wizard",
"level":44
}
You can decide to use the alpha name, or the level, or place "wizard" classes higher than others when you sort object arrays using the usort()
PHP routine. Just provide a function which implements those rules, whatever they might be. This answer has an example.
UPDATE: OP wants to detect ties
You can iterate through the list to detect sets where there are score ties. In psuedocode:
for each item in scorelist:
// create hash of score->list of items
scoreRef[item.score].append(item)
// scoreRef is a hash of scores => list of
// items that share that score.
for each item in scoreRef:
// item is an array
if item.size > 1:
tiebreakerList.append( item);
// tiebreakerList is a list of lists where
// the subordinate list items all share the same
// number of points
Upvotes: 3