【发布时间】:2019-03-05 09:51:26
【问题描述】:
我无法弄清楚如何解决这个问题,它来自一个免费的在线测试网站。这是链接:https://www.testdome.com/questions/php/league-table/19939?questionIds=7278,19939&generatorId=30&type=fromtest&testDifficulty=Hard
但为了更清楚,我也在写这个问题和我的答案。开始的答案在上面写的链接中。
问题:
LeagueTable 类跟踪联盟中每个玩家的得分。每场比赛结束后,玩家使用 recordResult 函数记录他们的得分。
玩家在联赛中的排名使用以下逻辑计算:
得分最高的玩家排名第一(排名 1)。得分最低的玩家排名最后。 如果两名球员得分相同,则比赛次数最少的球员排名较高。 如果两名球员的得分和比赛次数并列,那么在球员名单中排名第一的球员排名更高。 实现 playerRank 函数,返回给定排名的玩家。
例如:
$table = new LeagueTable(array('Mike', 'Chris', 'Arnold'));
$table->recordResult('Mike', 2);
$table->recordResult('Mike', 3);
$table->recordResult('Arnold', 5);
$table->recordResult('Chris', 5);
echo $table->playerRank(1);
所有玩家的得分相同。不过,阿诺德和克里斯的比赛场次都比迈克少,而且由于克里斯在球员名单中排在阿诺德之前,所以他排名第一。因此,上面的代码应该显示“Chris”。
我的代码:
<?php
class LeagueTable
{
public function __construct($players)
{
$this->standings = array();
foreach($players as $index => $p)
{
$this->standings[$p] = array
(
'index' => $index,
'games_played' => 0,
'score' => 0
);
}
}
public function recordResult($player, $score)
{
$this->standings[$player]['games_played']++;
$this->standings[$player]['score'] += $score;
}
public function playerRank($rank)
{
// I'm not sure what to do in here, not even sure where to place the conditional statements
// but here's me trying to figure it out which I'm 90% sure I'm doing it wrong,
// since I'm using too many foreach function and arrays. Most probably not even close
// to the correct answer.
$comparison = $result = $this->standings;
$player_names = array();
foreach($this->standings as $name => $records)
{
foreach($comparison as $name_compare => $records_compare)
{
if($this->standings[$name]['score'] > $comparison[$name_compare]['score'])
{
$result[$name]['index'] = $this->standings[$name]['index'];
}
else if($this->standings[$name]['score'] == $comparison[$name_compare]['score']
&& $this->standings[$name]['games_played'] < $comparison[$name_compare]['games_played'])
{
$result[$name]['index'] = $this->standings[$name]['index'];
}
else if($this->standings[$name]['score'] == $comparison[$name_compare]['score']
&& $this->standings[$name]['games_played'] == $comparison[$name_compare]['games_played'])
{
$result[$name]['index'] = $this->standings[$name]['index'];
}
// This is where I'm confused, although there are conditional statemens there
// but the code inside each "if" and "else if" is the same.
}
}
foreach($result as $name => $records)
{
array_push($player_names,$name);
}
return $player_names[$rank-1]; //This should return "Chris" based on the record result, but it's not
}
}
$table = new LeagueTable(array('Mike', 'Chris', 'Arnold'));
$table->recordResult('Mike', 2);
$table->recordResult('Mike', 6);
$table->recordResult('Arnold', 5);
$table->recordResult('Chris', 5);
echo $table->playerRank(1);
谁能帮我解决这个问题?
【问题讨论】:
-
按
usort函数排序数组 - php.net/manual/en/function.usort.php -
谢谢,但我仍然不知道如何应用
usort函数来回答这个问题。如果您能在答案部分告诉我您的方式,我将不胜感激,以便我更好地理解并了解有关数组排序的更多信息