2

我正在研究生成运动队的代码。我有一个包含球员列表的数组,并希望将所有可能的团队组合存储在另一个数组中。

为简单起见,让我们想象一场网球比赛,其中有 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;
    }
4

2 回答 2

2

刚刚用谷歌搜索并从 stackoverflow.com 找到了这些结果

获取 PHP 数组的所有组合

算法将采用数字或单词并找到所有可能的组合

PHP:如何获得一维数组的所有可能组合?

于 2013-03-08T15:42:26.470 回答
0

$player_combination = []; $match_combination = [];

  $players = array("Federer","Del Potro","Nadal","Murray");
  for($i = 0; $i< count($players);$i++){
      for($j=$i+1;$j<count($players);$j++){
        $player_combination[] = [$players[$i],$players[$j]]; 
       }
  }

  for($i = 0; $i< count($player_combination);$i++){
      for($j=$i+1;$j<count($player_combination);$j++){
        if(($player_combination[$i][0] !== $player_combination[$j][0]) &&  ($player_combination[$i][0] !== $player_combination[$j][1])&& ($player_combination[$i][1] !== $player_combination[$j][0]) && ($player_combination[$i][1] !== $player_combination[$j][1]))
        $match_combination[] = [$player_combination[$i],$player_combination[$j]]; 
       }
  }

我的网站是9amobile.com

于 2020-01-10T11:19:52.517 回答