Most efficient way to build a random permutations list

谁都会走 提交于 2019-12-22 17:52:22

问题


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 Games between Teams. 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.


回答1:


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


来源:https://stackoverflow.com/questions/20445290/most-efficient-way-to-build-a-random-permutations-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!