我实际上花了一些时间并编写了答案。这是一个非常有趣的问题。有很多方法可以解决这个问题:
- 花式迭代
- 递归
- 退出团队时进行迭代
- 使用单独的结构将团队“标记”为已处理
这张图片可能会有所帮助:
0 1 2 3
0 - A A A
1 B - A A
2 B B - A
3 B B B -
该矩阵的 X 和 Y 轴显示您想要的答案。Set A 或 Set B 都会给你答案。请注意,您不希望团队像矩阵中的破折号所示那样自行比赛。以下是使用迭代的 3 个选项:
public class BBall {
public static void main(String args[]) {
List<String> teams = new ArrayList<String>();
teams.add("Boston");
teams.add("LA");
teams.add("New York");
teams.add("Chicago");
teams.add("Dallas");
// This option might be a little easier to read.
int index1 = 0;
System.out.println("Easy to read:");
for (String team1 : teams) {
index1++;
for (int index2 = index1; index2 < teams.size(); ++index2) {
System.out.println(team1 + " plays " + teams.get(index2));
}
}
System.out.println("This is set A:");
for (int x = 1; x < teams.size(); x++) {
for (int y = x - 1; y >= 0; y--) {
System.out.println(teams.get(x) + " plays " + teams.get(y));
}
}
System.out.println("This is set B:");
for (int x = 0; x < teams.size() - 1; x++) {
for (int y = x + 1; y < teams.size(); y++) {
System.out.println(teams.get(x) + " plays " + teams.get(y));
}
}
}
}
输出:
易于阅读:
Boston plays LA
Boston plays New York
Boston plays Chicago
Boston plays Dallas
LA plays New York
LA plays Chicago
LA plays Dallas
New York plays Chicago
New York plays Dallas
Chicago plays Dallas
这是设置A:
LA plays Boston
New York plays LA
New York plays Boston
Chicago plays New York
Chicago plays LA
Chicago plays Boston
Dallas plays Chicago
Dallas plays New York
Dallas plays LA
Dallas plays Boston
这是B组:
Boston plays LA
Boston plays New York
Boston plays Chicago
Boston plays Dallas
LA plays New York
LA plays Chicago
LA plays Dallas
New York plays Chicago
New York plays Dallas
Chicago plays Dallas