【问题标题】:PHP simple game to found out which player should be wonPHP简单游戏找出应该赢得哪个玩家
【发布时间】:2021-06-24 02:47:09
【问题描述】:

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

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

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

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

然而,PeleZidane 的比赛次数比 Mike 少,并且由于 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';
}

【问题讨论】:

  • 如果这是连续流,或者它已经有一组定义的数据?
  • @nice_dev 应该有一组已定义的数据
  • 那么你可以简单地使用usort()
  • @nice_dev 你能帮我怎么用吗?
  • 这能回答你的问题吗? In php how does usort() function works

标签: php


【解决方案1】:

这可以通过array_multisort() 轻松完成,因为我们可以使订单依赖。但要做到这一点,我们需要创建一个新的数据结构,因为关联键不会更改,只会更改索引。

由于你的结构中的'key'保留了添加的顺序和$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);

齐达内

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多