我正在开发基于循环调度算法的 Java 体育赛事。对于n
团队,我想生成2(n-1)
带有n/2
比赛的回合。也就是每支球队必须打一场比赛,每2支球队交手两次,一次客场,一次主场。除了家庭/离开部分,我设法实现了算法。我能够生成回合,但不能在回合的后半段“交换”球队,所以他们在客场和主场比赛。
这是我到目前为止所拥有的:
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();
}
}
}
不要介意偶数/奇数队,现在我只对偶数队数感兴趣。