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

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

问题描述

对于给定的 CollectionaCollection,如何构建一个 ArrayList>,其中包含 aCollection 中所有可能的配对排列(自耦合除外).>

例如,假设 aCollection 是包含 teamAteamBSetteamCOrderedCouple 是一个 Game 类,它的构造函数接收两个团队,主机和访客作为参数.我想在 Team 之间构建所有可能的 GameArrayList.也就是说,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 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);
    }
}

prints something like this:

C : A
B : A
A : C
C : B
B : C
A : B

这篇关于构建随机排列列表的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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