如果存在平局,我如何对数组值进行排名并使用决胜局?

时间:2013-07-29 14:35:16

标签: php

我正在制作一款游戏,将每场比赛的前两名“得分”列为优胜者。

如果两个分数相同,则必须有一个决胜局(除非两个匹配分数分别位于第一和第二位)。

我如何(有效地)创建一个函数来返回以下可能性的结果:

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

        }

    }

}
?>

1 个答案:

答案 0 :(得分:3)

我的猜测是你作为你排名的对象的一部分得分超过分数(否则,重要的是“哪个”原始分数是第一个?)。在用于比较结果的比较器中,您可以考虑任何其他数据。所以,如果你的对象看起来像这样(JSON对象格式,而不是PHP。原谅):

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

使用usort() PHP例程对对象数组进行排序时,可以决定使用字母名称或级别,或者将“向导”类放在比其他类更高的位置。只需提供一个实现这些规则的功能,无论它们是什么。 This answer has an example.

更新: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