2013-02-17 70 views
1

這裏是我的代碼:夾具發生器代碼

$totalRounds = 1; 
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4', 'Team 5'); 
echo 'Total Teams: ' , $totalTeams = count($teams) , '<br/>'; 
$turns = $totalTeams; 

for($round=1; $round<$totalRounds+1; $round++){ 
    echo 'Round: ' , $round , '<br/>'; 

    for($homeTeam=0; $homeTeam<$totalTeams-1; $homeTeam++){ 
     for($awayTeam=0; $awayTeam<$totalTeams; $awayTeam++){ 
      if($teams[$homeTeam] != $teams[$awayTeam]){ 
       echo $teams[$homeTeam] , ' v/s ' , $teams[$awayTeam] , '<br/>'; 
      }       
     } 
     unset($teams[$homeTeam]); 
    } 
    echo '<br/>'; 
} 

我的預期輸出是:

Team 1 v/s Team 2 <br/> 
Team 1 v/s Team 3 <br/> 
Team 1 v/s Team 4 <br/> 
Team 1 v/s Team 5 <br/> 
Team 2 v/s Team 3 <br/> 
Team 2 v/s Team 4 <br/> 
Team 2 v/s Team 5 <br/> 
Team 3 v/s Team 4 <br/> 
Team 3 v/s Team 5 <br/> 
Team 4 v/s Team 5 <br/> 

我的實際產量是給我不確定的指數錯誤

一旦這個固定我不知道如何分配主隊和客隊。例如。團隊1應該只有2個主場比賽,而不是4個。每個團隊將參加2場主場比賽和2場客場比賽。

回答

1

你的代碼被破壞了數組,因爲它去,如:

first iteration: $home = 0; $away = 0 
end of iteration: delete teams[0] 

second iteration, $home = 1; $away = 0 - OOPS, teams[0] no longer exists 

,而不是你重置,當您去的數組,你應該立足於外環內循環,例如:

for($home = 0; ...) { 
    for($away = $home + 1; ...) { 
1

您可以通過以下

$totalRounds = 1; 
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4', 'Team 5'); 
echo 'Total Teams: ' , $totalTeams = count($teams) , '<br/>'; 
$turns = $totalTeams; 

for($round=1; $round<$totalRounds+1; $round++){ 
    echo 'Round: ' , $round , '<br/>'; 

    for($homeTeam = 0; $homeTeam < $totalTeams - 1; $homeTeam++) { 
     for($awayTeam=$homeTeam + 1; $awayTeam < $totalTeams; $awayTeam++) { 
      echo $teams[$homeTeam] , ' v/s ' , $teams[$awayTeam] , '<br/>'; 
     } 
    } 
    echo '<br/>'; 
} 
+0

感謝您的解決方案馬克 - 菲利普解決您的代碼。我如何爲每個團隊獲得兩場主場比賽和兩場客場比賽? – Learning2Kode 2013-02-18 05:55:45