I am developing a sport torunament in Java based on round robin scheduling algorithm. For n
teams I want to generate 2(n-1)
rounds with n/2
matches. That is that every team must play a match in a round, and every 2 teams meet twice, once away and once home. I managed to implement the algoritm except for the home/away part. I am able to generate the rounds, but can not "swap" the teams in the second half of rounds so they play both away and home.
Here is what I have so far:
public class sports {
public static void main(String[] args) {
//obtain the number of teams from user input
Scanner input = new Scanner(System.in);
System.out.print("How many teams should the fixture table have?");
int teams = input.nextInt();
// Generate the schedule using round robin algorithm.
int totalRounds = (teams - 1) * 2;
int matchesPerRound = teams / 2;
String[][] rounds = new String[totalRounds][matchesPerRound];
for (int round = 0; round < totalRounds; round++) {
for (int match = 0; match < matchesPerRound; match++) {
int home = (round + match) % (teams - 1);
int away = (teams - 1 - match + round) % (teams - 1);
// Last team stays in the same place
// while the others rotate around it.
if (match == 0) {
away = teams - 1;
}
// Add one so teams are number 1 to teams
// not 0 to teams - 1 upon display.
rounds[round][match] = ("team " + (home + 1)
+ " plays against team " + (away + 1));
}
}
// Display the rounds
for (int i = 0; i < rounds.length; i++) {
System.out.println("Round " + (i + 1));
System.out.println(Arrays.asList(rounds[i]));
System.out.println();
}
}
}
Don't mind even/odd number of teams, for now I am only interested in even teams number.