1

Here's my code:

$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/>';
}

My expected output is:

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/>

My actual output is giving me undefined index errors

Once this is fixed I don't know how to assign home and away teams. Eg. Team 1 should have only 2 home games, instead it has 4. Each team will play 2 home games and 2 away games.

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; ...) {
于 2013-02-17T23:49:48.660 回答
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/>';
}
于 2013-02-17T23:50:42.277 回答