简体   繁体   English

列出一组元素的所有组合

[英]Listing all the combinations of the elements of a set

Among elements of a set, I want to list all the 3-combinations of this set. 在集合的元素中,我想列出该集合的所有3个组合。 Is there a way to do it? 有办法吗?

If it was a list; 如果是列表;

for(int i=0; i<list.size()-2; i++)
    for(int j=i+1; j<list.size()-1; j++)
        for(int k=j+1; k<list.size(); k++)
            System.out.println(list.get(i) + " " + list.get(j) + " " + list.get(k));

But how to do this with a set without converting it to a list? 但是,如何在不将其转换为列表的情况下使用集合呢?

Converting to a list and using the logic from your code would be my first choice. 首选是转换为列表并使用代码中的逻辑。 If you want to do it without converting to list, you can do it with iterators, like this: 如果要执行此操作而不转换为列表,则可以使用迭代器进行操作,如下所示:

Set<String> set = ...;
for (String a : set) {
    boolean bGo = false;
    for (String b : set) {
        if (bGo) {
            boolean cGo = false;
            for (String c : set) {
                if (cGo) {
                    System.out.println(a + " " + b + " " + c);
                } else if (b.equals(c)) {
                    cGo = true;
                }
            }
        } else if (a.equals(b)) {
            bGo = true;
        }
    }
}

The logic above freely iterates the set in the outer loop. 上面的逻辑在外循环中自由迭代集合。 When it starts iterating the set in the first nested loop, it skips elements until the current element of the outer loop is found (ie until a.equals(b) ). 当它开始迭代第一个嵌套循环中的集合时,它将跳过元素,直到找到外部循环的当前元素为止(即直到a.equals(b) )。 After that, it runs the third nested loop, which skips all data in the set until b , at which point it starts producing the combinations output. 之后,它将运行第三个嵌套循环,该循环将跳过集合中的所有数据,直到b为止,这时它将开始产生组合输出。

Here is a demo on ideone. 这是有关ideone的演示。

Is your set a SortedSet ? 您设置的是SortedSet吗? If so, you can do this: 如果是这样,您可以这样做:

for (V x: mySet) {
  for (V y: mySet.tailSet(x, false)) {
    for (V z: mySet.tailSet(y, false)) {
      System.out.println(x + " " + y + " " + z);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM