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.
Asked
Active
Viewed 1,725 times
1
-
is this homework; if yes please re-tag it. First of all you should let us know what you did about this? – Bharat Sinha Aug 14 '12 at 04:24
1 Answers
4
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;
}

Louis Wasserman
- 191,574
- 25
- 345
- 413