对于给定的Collection<Object> aCollection
, 如何构建 ArrayList<OrderedCouple<Object>>
以及 aCollection
中所有可能的情侣排列(自耦合除外)。
例如,说 aCollection
是 Set<Team>
包含teamA
, teamB
和teamC
,和OrderedCouple
而是一个类 Game<Team>
该构造函数接收两个团队(主机和访客)作为参数。
我想建立一个ArrayList
所有可能的Game
介于 Team
之间s。即ArrayList
将是组{new Game(teamA, teamB), new Game(teamA, teamC), new Game(teamB, teamA), new Game(teamB, teamC), new Game(teamC, teamA), new Game(teamC, teamB)}
以随机顺序排列。
最佳答案
我想不出比这更快的方法了:
@Test
public void buildMatchUps() {
List<String> teams = Arrays.asList("A", "B", "C");
int s = teams.size() * teams.size() - teams.size();
List<String> matchUps = new ArrayList<String>(s);
for(String host : teams) {
for(String guest : teams) {
if(host != guest) { // ref comparison, because the objects
// come from the same list. Otherwise
// equals should be used!
matchUps.add(host + " : " + guest);
}
}
}
Collections.shuffle(matchUps);
for(String matchUp : matchUps) {
System.out.println(matchUp);
}
}
打印如下内容:
C : A
B : A
A : C
C : B
B : C
A : B
关于java - 构建随机排列列表的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445290/