如果我们有四支球队,我们可以写出所有可能的匹配排列,如下所示:
(1, 1) (1, 2) (1, 3) (1, 4)
(2, 1) (2, 2) (2, 3) (2, 4)
(3, 1) (3, 2) (3, 3) (3, 4)
(4, 1) (4, 2) (4, 3) (4, 4)
您可以看到在对角线上镜像的重复。
我使用以下代码输出上述内容:
for($i=1; $i<5; $i++) {
for($j=1; $j<5; $j++) {
echo "($i, $j) ";
}
echo "\n";
}
如果我们只关心 $i 小于 $j 的对联。或者,在 $i 大于 $j 的情况下,我们剔除重复项和对角线本身(团队自己比赛的地方)。
function team_combinations($no_teams) {
$combinations = array();
for($i=1; $i<=$no_teams; $i++) {
for($j=1; $j<=$no_teams; $j++) {
if($i < $j)
$combinations[] = array($i, $j);
}
}
return $combinations;
}
var_export(team_combinations(4));
输出:
array (
0 =>
array (
0 => 1,
1 => 2,
),
1 =>
array (
0 => 1,
1 => 3,
),
2 =>
array (
0 => 1,
1 => 4,
),
3 =>
array (
0 => 2,
1 => 3,
),
4 =>
array (
0 => 2,
1 => 4,
),
5 =>
array (
0 => 3,
1 => 4,
),
)