Generating nCr combinations of given set in java

1.7k Views Asked by At

I want java implementation of generating nCr combinations of given set. e.g if set is {"java","php",".net","python"} program should return all possible nCr sets of given set.

1

There are 1 best solutions below

0
On

Adapting Gosper's hack, this works up to n = 64.

List<String> inputs;
List<List<String>> ncr = new ArrayList<List<String>>();
for (long x = (1 << r) - 1; (x >>> r) == 0;) {
  // x contains a 1 bit for each input we should choose;
  // iterate over the 1 bits of x
  long y = x;
  List<String> combination = new ArrayList<String>();
  for (int i = Long.numberOfTrailingZeros(y);
       y != 0; i = Long.numberOfTrailingZeros(y)) {
    combination.add(inputs.get(i));
    y &= ~(1 << i);
  }
  long u = x & -x;
  long v = u + x;
  x = v + ((v ^ x) / u) >>> 2;
}