构建随机排列列表的最有效方法 [英] Most efficient way to build a random permutations list
问题描述
对于给定的 Collection
,如何构建一个 ArrayList
,其中包含 aCollection
中所有可能的配对排列(自耦合除外).>
例如,假设 aCollection
是包含 teamA
、teamB
和 的
和 Set
teamCOrderedCouple
是一个 Game
类,它的构造函数接收两个团队,主机和访客作为参数.我想在 Team
之间构建所有可能的 Game
的 ArrayList
.也就是说,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公共无效 buildMatchUps() {列表<字符串>团队 = Arrays.asList("A", "B", "C");int s = team.size() * team.size() - team.size();列表<字符串>matchUps = new ArrayList(s);for(字符串主机:团队){for(字符串来宾:团队){if(host != guest) {//ref 比较,因为对象//来自同一个列表.除此以外//应该使用等号!matchUps.add(host + " : " + 客人);}}}Collections.shuffle(matchUps);for(字符串匹配:匹配){System.out.println(matchUp);}}
打印如下:
C : A乙:甲: 丙乙:乙乙:丙: 乙
For a given Collection<Object> aCollection
, How do I build an ArrayList<OrderedCouple<Object>>
with all possible permutations of couples in aCollection
(except self-coupling).
For instance, say aCollection
is a Set<Team>
containing teamA
, teamB
and teamC
, and OrderedCouple
is instead a class Game<Team>
which constructor receives two team, the host and the guest as arguments.
I want to build an ArrayList
of all possible Game
s between Team
s. that is, the ArrayList
will be the group {new Game(teamA, teamB), new Game(teamA, teamC), new Game(teamB, teamA), new Game(teamB, teamC), new Game(teamC, teamA), new Game(teamC, teamB)}
in a random order.
I can't think of a faster way than this:
@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);
}
}
prints something like this:
C : A
B : A
A : C
C : B
B : C
A : B
这篇关于构建随机排列列表的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!