如何对数组中的项进行配对?假设我有一组战士,。我想根据他们的权重把他们配对。最接近重量的拳击手应该配对为最佳匹配。但如果他们是在同一个团队,他们不应该是配对的。
- 1--**
输出:
我一直在研究这个话题,并发现了一些类似但不完全相同的东西:Random But Unique Pairings, with Conditions
会很感激你的帮助。提前感谢!
发布于 2012-02-11 11:19:06
我很喜欢你的问题,所以我做了一个完整的版本。
<?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(),通过数组和匹配来根据每个usort()的权重属性对数组进行排序:,
)。
当找到匹配时,将每个匹配战斗机的对象指针存储到对方(因此它不再为null ),并且可以通过$fighterVariable->paired)
发布于 2012-02-11 10:51:50
按权重对数组进行排序。然后,你们将有一对重物互相接近。
https://stackoverflow.com/questions/9239598
复制相似问题