【问题标题】:Most efficient way to build a random permutations list构建随机排列列表的最有效方法
【发布时间】:2013-12-07 19:00:58
【问题描述】:

对于给定的Collection<Object> aCollection,我如何构建一个ArrayList<OrderedCouple<Object>>,其中包含aCollection 中所有可能的组合排列(自耦合除外)。

例如,假设aCollection 是一个包含teamAteamBteamCSet<Team>,而OrderedCouple 是一个类Game<Team>,它的构造函数接收两个团队,主机和客人作为论据。 我想在Teams 之间构建所有可能的Games 的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)} 的随机顺序。

【问题讨论】:

标签: java random arraylist coupling


【解决方案1】:

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

@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

【讨论】:

  • 请注意,此代码在O(n^2) 中运行。更具体地说,使用k = teams.size(),它在O(n^k) 中运行。但是对于小团队和少量固定数量(本例中为 2 个团队),它可以正常工作。
  • @Elist 使用这段代码,然后创建一个Game对象的List,然后调用Collections.shuffle(yourGameList);,那么它是随机的。
  • @skiwi 感谢您的编辑,我打算使用与 != 进行比较,因为对象应该是相同的。顺便说一句equals 在继续之前也会做同样的检查:)
  • 好的,感谢您将我介绍给Collections.shuffle(),看来这就是我要寻找的东西...为了完整起见,请将其添加到您的答案中。无论如何,如果有人知道Collections.shuffle() 的时间复杂度,并且如果有更有效的方法(可能在无序列表上进行迭代),我仍然想在这里
  • @skiwi here teams.size() == 3 但代码在O(n^2) 中运行,所以它不是o(n^k)
猜你喜欢
  • 2010-12-15
  • 2010-09-27
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多