简体   繁体   中英

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. 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) ). 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.

Here is a demo on ideone.

Is your set a 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);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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