【问题标题】:Randomly generate pair team, not pairing with itself随机生成pair team,不与自己配对
【发布时间】:2014-01-20 11:28:20
【问题描述】:

我想生成一个配对结构,我只有 n(团队数)和级别(n-1)

请看截图: 首先是四分之一决赛,每队随机配对8支队伍。

四分之一决赛:

 Austria->paired with = Hungary
 Czech Republic->paired with = New Zealang
 France->paired with = Belgium
 Estonia->paired with = Iceland

使用 PHP,您如何将团队随机配对而不将他们与自己的副本配对?

编辑:所有八支球队都来自数据库。

【问题讨论】:

  • 团队信息是否来自数据库,因为使用 sql 可以轻松做到这一点?
  • @gprusiiski 是的,所有团队都来自数据库

标签: php random generator


【解决方案1】:

如果您有团队列表,则可以将其添加到从零开始的数组中。可以修改以下给定的代码示例以满足您的要求。根据您的情况更改/修改它以动态获取团队并处理奇数/偶数团队计数。跟随 for 循环仅适用于偶数团队,所以剩下的就交给你了。

$teams[] = "Austria";
$teams[] = "Hungary";
$teams[] = "Czech Republic";
$teams[] = "New Zealang";
$teams[] = "France";
$teams[] = "Belgium";
$teams[] = "Estonia";
$teams[] = "Iceland";

$number_of_teams = count($teams);
// Shuffle the teams
shuffle($teams);// You get a shuffled array

// Pair the adjacent teams
for ( $index = 0; $index < $number_of_teams; $index +=2) {
    // Pair $teams[$index ] with $teams[$index +1]
    echo $teams[$index ] . "->paired with = " . $teams[$index+1] . "<br>";
}

【讨论】:

【解决方案2】:

使用随机洗牌,而不是随机选择。将八支队伍排成一排,洗牌。这样你就可以保证没有重复,每个团队仍然出现一次,但顺序不同。

【讨论】:

猜你喜欢
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
相关资源
最近更新 更多