【问题标题】:How do I rank array values and use a tiebreaker when there is a tie?当出现平局时,如何对数组值进行排名并使用决胜局?
【发布时间】:2013-07-29 14:35:16
【问题描述】:

我正在创建一个游戏,它将每场比赛的前 2 个最高“分数”标记为获胜者。

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

我怎样才能(有效地)创建一个函数,为以下可能性返回这些结果:

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

        }

    }

}
?>

【问题讨论】:

  • 我注意到在很多游戏中,如果出现平局,那么最后一个玩家将获得积分。
  • 作为另一个考虑因素,如果第一名是三人并列,那么是三人决胜局,一名获胜者,然后是两人决胜局,一名获胜者?还是会是一个有两个获胜者的三人决胜局?
  • @ChrisForrence - 三人决胜局,两名获胜者。
  • @diegoperini 虽然可以从该问题中收集到一些相关信息,但我想说这两个问题的不同之处足以不被视为重复

标签: php


【解决方案1】:

我的猜测是,作为要排名的对象的一部分,您有多个分数(否则,“哪个”原始分数是第一重要吗?)。在您用来比较结果的比较器中,您可以考虑任何其他数据。所以,如果你的对象真的看起来像这样(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

【讨论】:

  • 我实际上想要检查是否有平局,因为当两个分数相同且没有两个明确的赢家时,会有单独的决胜局游戏。
  • 相反,然后遍历排序列表,找到有平局的对/组,并将对/组添加到决胜局游戏列表中。
猜你喜欢
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多