Create all unique item combinations

I am trying to create every possible unique combination of elements.

Ex: item1, item2, item3

Combinations: 
   item1+item2+item3
   item1+item2
   item1+item3
   item2+item3
   item1
   item2
   item3

I can’t figure out how to solve this?

for(int i=0;i<size;i++){
   for(int j=i+1;j<size;j++){
       System.out.println(list.item(i)+list.item(j));
   }
}

The above code certainly works for the entire unique combination of the two elements. But not for a pair of three elements, etc.

+4
source share
3 answers

If you have N items, count from 1 to 2 ^ N-1. Each number represents a combination, for example: if bit 0 (the least significant bit) is set, item1 is in combination. If bit 1 is set, item2 is in combination, etc.

1 , 3 , 2 (4, 8, 16 ..).

+7

guava ,

 Set<Set<String>> result = Sets.powerSet(Sets.newHashSet("item1", "item2", "item3"));
    for(Set<String> token : result){
        System.out.println(token);
    }
+4

The following Java solution uses the bit approach proposed by zmbq :

  public static void allComb(int n) {
    BitSet bs = new BitSet();
    while (bs.length() <= n) {
      System.out.println(bs);
      //Inc by 1
      int pos = bs.nextClearBit(0);
      bs.flip(0, pos + 1);      
    }
  }
+2
source

Source: https://habr.com/ru/post/1524235/


All Articles