php - PHP简单游戏找出应该赢得哪个玩家
问题描述
在这个简单游戏的联赛表结构中PHP
,我们想要跟踪联赛中每个玩家的得分,我们使用以下代码传递并定义玩家的每个得分:
$table->save_result('Albert', 2); //albert with 2 score
$table->save_result('Albert', 3);//albert with 3 score
这里有一些提示:
玩家在联赛中的排名使用以下逻辑计算:
- 1-得分最高的玩家排名第一(排名1)。得分最低的玩家排名最后。
- 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);
现在如果两个玩家得分相同,那么谁玩过,那么谁在玩家列表中排名第一的玩家排名更高。
然而Pele
,Zidane
他打的比赛比迈克少,而且和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';
}
解决方案
使用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);
齐达内
推荐阅读
- java - VBO 纹理未渲染
- android - React Native:Null 不是对象 - 推送通知 (OneSignal)
- c - 在C中返回指向字符串的指针时出现问题
- javascript - Node.js / Express.js - 我应该将我的所有函数都包装在一个新的 Promise 中吗?
- c# - 数据库优先到代码优先 EF - 迁移键和约束名称与数据库不匹配
- django - 无法从表单创建对象
- android - 在 iOS 和 Android 上动态更改应用程序图标
- istio - 将 K8s Ingress 与 Istio 网关一起使用?
- firebase - Arduino wifi > firebase 和超过 1 个 LED 控制
- python - 美丽的汤没有为使用相同 URL 的两个不同程序找到相同的结果