如何配对数组中的项目?假设我有一系列战士.我想根据他们的重量配对它们.最接近重量的战斗机应配对为最佳匹配.但如果他们在同一个团队中,他们就不应该配对.
输出:
我一直在研究这个主题,发现了类似但不完全的东西: 随机但独特的配对,有条件
非常感谢一些帮助.提前致谢!
我非常喜欢您的问题,所以我做了一个完整的版本。
<?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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
usort()和排序功能sortFighters()按每个元素的weight属性进行排序。$fighterVariable->paired)