建立一个随机排列列表最有效的方法 [英] Most efficient way to build a random permutations list

查看:220
本文介绍了建立一个随机排列列表最有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的收集和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 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.

推荐答案

我想不出比这更快的方法:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆