首页 > 解决方案 > PHP简单游戏找出应该赢得哪个玩家

问题描述

在这个简单游戏的联赛表结构中PHP,我们想要跟踪联赛中每个玩家的得分,我们使用以下代码传递并定义玩家的每个得分:

$table->save_result('Albert', 2); //albert with 2 score
$table->save_result('Albert', 3);//albert with 3 score

这里有一些提示:

玩家在联赛中的排名使用以下逻辑计算:

  1. 1-得分最高的玩家排名第一(排名1)。得分最低的玩家排名最后。
  2. 2- 如果两名球员得分相同,则比赛次数最少的球员排名较高。

用分数保存玩家的基类:

class Table
{
    private $standings = [];

    public function __construct(array $players)
    {
        $this->data = [];
        foreach($players as $key => $p) {
            $this->data[$p] = [
                'key'        => $key,
                'games_played' => 0,
                'player_score'        => 0
            ];
        }
    }

    public function save_result(string $player, int $score)
    {
        $this->data[$player]['games_played']++;
        $this->data[$player]['player_score'] += $score;
    }
}

现在我们有 2 个玩家得分相同,例如:

$table->save_result('Pele', 5);
$table->save_result('Zidane', 5);

现在如果两个玩家得分相同,那么谁玩过,那么谁在玩家列表中排名第一的玩家排名更高。

然而PeleZidane他打的比赛比迈克少,而且和Zidane以前一样Pele,他在球员名单中排名第一。因此,正确的结果应该Zidane是,例如:

$table = new Table(array('Albert', 'Pele', 'Zidane'));

$table->save_result('Albert', 2); //albert with 2 score
$table->save_result('Albert', 3);//albert with 3 score
$table->save_result('Pele', 5);
$table->save_result('Zidane', 5);
echo $table->get_rank_result(1);

我们如何在下面的函数中计算这个分数?我做不到

public function get_rank_result(int $rank) : string
{
   // should be return 'Zidane';
}

标签: php

解决方案


使用array_multisort()可以很容易地做到这一点,因为我们可以使顺序相关。但要做到这一点,我们需要创建一个新的数据结构,因为关联键没有改变,只有索引。

由于结构中的“键”保持添加的顺序和名称键$this->data,我们可以取回名称。

public function get_rank_result(int $rank) : string
{
    $data = [
        array_column($this->data, 'player_score'),
        array_column($this->data, 'games_played'),
        array_column($this->data, 'key'),
    ];

    array_multisort(
        $data[0], SORT_DESC, SORT_NUMERIC,
        $data[1], SORT_ASC, SORT_NUMERIC,
        $data[2], SORT_DESC, SORT_NUMERIC,
    );

    return array_keys($this->data)[array_search($data[2][$rank - 1], array_column($this->data, 'key'))];
}
echo $table->get_rank_result(1);

齐达内


推荐阅读