我正在研究生成运动队的代码。我有一个包含球员列表的数组,并希望将所有可能的团队组合存储在另一个数组中。
为简单起见,让我们想象一场网球比赛,其中有 4 名球员将被分成两队。
$players = array("Federer","Del Potro","Nadal","Murray");
输出数组应如下所示:
$combinations[0][0] = "Federer","Del Potro";
$combinations[0][1] = "Nadal","Murray";
$combinations[1][0] = "Federer","Nadal";
$combinations[1][1] = "Del Potro","Murray";
$combinations[2][0] = "Del Potro","Nadal";
$combinations[2][1] = "Federer","Murray"; .. and so forth..
有什么帮助吗?
提前致谢!
/// - 编辑
这是我到目前为止的代码。所有玩家也有一个分数,我存储这个分数供以后使用。它不是很重要。我想我已经让它工作了,但我不确定这段代码是否能得到所有可能的组合。我所做的是循环“玩家计数”时间并开始建立团队,在建立团队后,我将列表中的第二个玩家移动到数组的底部并再次循环。
//-- Get the Max Players and the Array of Player Names
$max_players = count($players)/2;
$p = array_keys($players);
for($i=0;$i<=(count($p));$i++){
$tmp = array();
$t=0;
//-- Loop and start placing players into a team. When the max is reached, start placing on the other team.
foreach($p as $player) {
//-- Store player on Team
$tmp[$t][] = $player;
if(count($tmp[$t])==$max_players) {
$t++;
}
}
//-- Get the second player and move it to the bottom of the list.
$second = $p[1];
unset($p[1]);
$p[] = $second;
$p = array_values($p);
//-- Loop thru teams and add the score of each player
foreach($tmp as $key=>$eq) {
$score = 0 ;
foreach($eq as $jug) {
//-- Add Score for each player
$score += floatval($players[$jug]["score"]);
}
//-- Store the sum of scores of all players in team
$tmp[$key]["score"] = $score;
}
//-- Store the Difference between team scores in this "team set"
$tmp["diff"] = abs(round($tmp[0]["score"]-$tmp[1]["score"],2));
$teams[] = $tmp;
}