BLOG.CSHARPHELPER.COM: Generate a schedule for a round robin tournament in C#
Generate a schedule for a round robin tournament in C#
Click here to see a description of the algorithm used.
Function GenerateRoundRobinOdd returns an array where results[i, j] gives the opponent of team i in round j of the tournament. This function works only for an odd number of teams. The link above explains the method.
private const int BYE = -1;
// Return an array where results(i, j) gives // the opponent of team i in round j. // Note: num_teams must be odd. private int [,] GenerateRoundRobinOdd(int num_teams) { int n2 = (int)((num_teams - 1) / 2); int[,] results = new int[num_teams, num_teams];
// Initialize the list of teams. int[] teams = new int[num_teams]; for (int i = 0; i < num_teams; i++) teams[i] = i;
// Start the rounds. for (int round = 0; round < num_teams; round++) { for (int i = 0; i < n2; i++) { int team1 = teams[n2 - i]; int team2 = teams[n2 + i + 1]; results[team1, round] = team2; results[team2, round] = team1; }
// Set the team with the bye. results[teams[0], round] = BYE;
// Rotate the array. RotateArray(teams); }
return results; }
Helper function RotateArray rotates the items in the team array. The algorithm calls this routine after each round.
// Rotate the entries one position. private void RotateArray(int[] teams) { int tmp = teams[teams.Length - 1]; Array.Copy(teams, 0, teams, 1, teams.Length - 1); teams[0] = tmp; }
Function GenerateRoundRobinEven returns a similar array for an even number of teams. It calls GenerateRoundRobinOdd to make a schedule for a tournament with one fewer teams. It then expands the result array and replaces the byes with the additional team. See the link above for a more complete explanation.
private int[,] GenerateRoundRobinEven(int num_teams) { // Generate the result for one fewer teams. int[,] results = GenerateRoundRobinOdd(num_teams - 1);
// Copy the results into a bigger array, // replacing the byes with the extra team. int[,] results2 = new int[num_teams, num_teams - 1]; for (int team = 0; team < num_teams - 1; team++) { for (int round = 0; round < num_teams - 1; round++) { if (results[team, round] == BYE) { // Change the bye to the new team. results2[team, round] = num_teams - 1; results2[num_teams - 1, round] = team; } else { results2[team, round] = results[team, round]; } } }
return results2; }
Function GenerateRoundRobin simply calls functions GenerateRoundRobinOdd and GenerateRoundRobinEven depending on whether the number of teams is odd or even.
Comments