我非常喜欢你的问题,所以我做了一个完整的健壮版本。
<?php
header("Content-type: text/plain");
error_reporting(E_ALL);
/**
* @class Fighter
* @property $name string
* @property $weight int
* @property $team string
* @property $paired Fighter Will hold the pointer to the matched Fighter
*/
class Fighter {
public $name;
public $weight;
public $team;
public $paired = null;
public function __construct($name, $weight, $team) {
$this->name = $name;
$this->weight = $weight;
$this->team = $team;
}
}
/**
* @function sortFighters()
*
* @param $a Fighter
* @param $b Fighter
*
* @return int
*/
function sortFighters(Fighter $a, Fighter $b) {
return $a->weight - $b->weight;
}
$fighterList = array(
new Fighter("A", 60, "A"),
new Fighter("B", 65, "A"),
new Fighter("C", 62, "B"),
new Fighter("D", 60, "B"),
new Fighter("E", 64, "C"),
new Fighter("F", 66, "C")
);
usort($fighterList, "sortFighters");
foreach ($fighterList as $fighterOne) {
if ($fighterOne->paired != null) {
continue;
}
echo "Fighter $fighterOne->name vs ";
foreach ($fighterList as $fighterTwo) {
if ($fighterOne->team != $fighterTwo->team && $fighterTwo->paired == null) {
echo $fighterTwo->name . PHP_EOL;
$fighterOne->paired = $fighterTwo;
$fighterTwo->paired = $fighterOne;
break;
}
}
}
- 首先,战士被分成不同的类别,这使得为他们分配属性变得更容易(如果你自己还没有这样做,我强烈建议你这样做!)
- 制作一组拳手,并为他们分配名字、体重和团队。
- 按权重对数组进行排序(使用
usort()
和排序功能sortFighters()
按每个元素的权重属性排序。
- Iterate through the array and match based on:
- 战斗机一号尚未匹配
- 战斗机二号与战斗机一号不在同一团队
- 战斗机二号尚未匹配
- 当找到匹配时,将每个匹配战斗机的对象指针存储到彼此(因此它不再为空,而且您可以通过访问每个战斗机对
$fighterVariable->paired
)
- 最后,打印结果。