建立一个随机排列列表最有效的方法 [英] Most efficient way to build a random permutations list
问题描述
对于给定的收集和LT;对象> aCollection
,如何建立一个的ArrayList< OrderedCouple<对象>>
在夫妻所有可能的排列 aCollection
(除自耦合)。
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).
例如,假设 aCollection
是设置&LT;团队及GT;
包含 teamA
, teamB
和 teamC
和 OrderedCouple
是不是类游戏&LT;后者构造接收两个团队,宾主作为参数
;团队及GT。
我想建立一个的ArrayList
所有可能的游戏
之间采用S 团队
秒。也就是说,的ArrayList
将成为集团 {新游戏(teamA,teamB),新游戏(teamA,teamC),新游戏(teamB, teamA),新游戏(teamB,teamC),新游戏(teamC,teamA),新游戏(teamC,teamB)}
以随机顺序。
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);
}
}
版画是这样的:
C : A
B : A
A : C
C : B
B : C
A : B
这篇关于建立一个随机排列列表最有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!