我有一个我一直在考虑的问题,但我无法弄清楚如何解决它。我正在为我的当地体育俱乐部编写软件,该俱乐部即将举办国际比赛。我希望尽可能自动化管理。我已经做了很多,但现在我很难完成最后一件事。
说,你有一个包含4个团队的阵列,即团队A,B,C和D.我想做的是创建一个包含所有可能游戏的新阵列。这并不难,但困难在于我希望在其中具有某种排序功能。我现在拥有它的方式,游戏就像这样创建:
['A - B', 'A - C', 'A - D', 'B - C' , ...]
我想拥有的是这样的:
['A - B', 'C - D', 'A - C', 'B - D', 'A - D', ...]
有谁知道我怎么能做到这一点?任何帮助将不胜感激。
旁注:A - B = B - A,我们不需要双向竞争(但如果需要,我可以自己编程)。
答案 0 :(得分:1)
这是一个简单的问题,更多的是MATRIX问题,结果是对角线
$队[0 ... n]的
$index=0;
for($i=0;$i<$n;$i++){
for($c=$i+1;$c<$n;$c++)
$matches[$index++]=$teams[$i]." - ".$teams[$c];
}
现在$ matches最终是一个匹配矩阵 要对它进行排序:
$sorted_games //You should pass on the matches diagonally and skipping one when possible
A B C D
AB --- --- AC AD
------- --- BC BD
-------------- CD
他们的指数是
0 --- 1 --- 2
- - - - 3 --- 4
---------- 5
沿对角方向行驶并尽可能跳过:
0然后是5(我们跳过3)
现在进入1
所以0 - 5 - 1
现在我们不跳过(因为不在主对角线上,所以我们采取4)
所以0 - 5 - 1 - 4
我们继续到2
所以0 - 5 - 1 - 4 - 2
最后我们回到主对角线并获得3
所以结果是0-5-1-4-2-3
并且比赛是:AB - CD - AC - BD - AD - BC
答案 1 :(得分:0)
我找到了解决问题的方法。 它显示如下:)
function sort_array($teams)
{
$num_teams = count($teams);
if(count($teams)%2 != 0)
{
$ghost = array();
$ghost["name"] = "ghost";
array_push($teams, $ghost);
$num_teams++;
}
$games = array();
for($i = 1; $i < $num_teams; $i++)
{
if($teams[$i]["name"] != "ghost")
array_push($games, $teams[0]["name"] . " - " . $teams[$i]["name"]);
for($k = 1; $k <= $num_teams; $k++)
{
$index_team_1 = ($i+$k < $num_teams) ? $i+$k : $i+$k-$num_teams;
$index_team_2 = ($i-$k > 0) ? $i-$k : $i-$k+$num_teams-1;
$temp_add = array();
$temp_add["team_1"] = $teams[$index_team_1]["name"];
$temp_add["team_2"] = $teams[$index_team_2]["name"];
if($teams[$index_team_1]["name"] != "ghost" &&
$teams[$index_team_2]["name"] != "ghost" &&
$index_team_1 != 0 &&
$index_team_2 != 0 &&
$temp_add["team_1"] != $temp_add["team_2"] &&
!in_array($temp_add["team_1"] . " - " . $temp_add["team_2"], $games) &&
!in_array($temp_add["team_2"] . " - " . $temp_add["team_1"], $games))
{
array_push($games, $temp_add["team_1"] . " - " . $temp_add["team_2"]);
}
}
}
return $games;
}