如何对数组值进行排序,并在出现平局时使用决胜局


How do I rank array values and use a tiebreaker when there is a tie?

我正在创建一个游戏,将每个游戏的前两名最高"分数"标记为获胜者。

如果其中两个分数相同,则必须进行决胜局(除非两个匹配的分数分别为第一和第二名)。

我如何(有效地)生成一个函数,返回以下可能性的这些结果:

6个不同游戏的可能游戏结果:

$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

编辑:解决方案:

<?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);                
        }
    }
}
?>

我的猜测是,作为排名对象的一部分,你有超过个分数(否则,"哪个"原始分数第一重要吗?)。在你用来比较结果的比较器中,你可以考虑任何额外的数据。所以,如果你的对象真的是这样的(JSON对象格式,而不是PHP。原谅):

{
"name":"frank",
"score":20,
"class":"wizard",
"level":44
}

当您使用usort()PHP例程对对象数组进行排序时,您可以决定使用alpha名称或级别,或者将"向导"类放置在比其他类更高的位置。只要提供一个函数来实现这些规则,不管它们是什么。这个答案有一个例子。

更新:OP想要检测关联

您可以在列表中进行迭代,以检测存在分数平局的集合。在伪码中:

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