我正在基于循环调度算法用 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();
}
}
}
不介意队伍的偶数/奇数,目前我只对偶数的队伍感兴趣。
最佳答案
整理 True Soft 的答案,
String roundString;
if (round < halfRoundMark) {
roundString = ("team " + (home + 1)
+ " plays against team " + (away + 1));
} else {
roundString = ("team " + (away + 1)
+ " plays against team " + (home + 1));
}
rounds[round][match] = roundString;
在哪里
int halfRoundMark = (totalRounds / 2);
关于java - 双循环赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20854371/