java - 双循环赛

标签 java schedule round-robin

我正在基于循环调度算法用 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/

相关文章:

java - spring如何将方法调用解析为bean?

mysql - 如何在 10 秒后执行 SQL 查询?

c# - 在指定时间引发事件

linux - 在 CFS 组调度中,我怎么知道 sched_entity 是叶实体(与实际任务相关联)?

mysql - MySQL 有没有办法对变量 Universe 中的特定字段执行 “round robin” ORDER BY ?

java - 将 RGB 值转换为颜色名称

Java 线程 - 线程局部变量

java - 我正在尝试将数据输入到 parse.com 中的 custommom 列,但出现错误

java - 以循环方式返回数字,但带有附加子句

java - 使用循环算法来计算所需时间