With n=5 and k=3 the following loop will do it
List l=new ArrayList();
l.add(\"A\");l.add(\"B\");l.add(\"C\");l.add(\"D\");l.add(\"E\
This technique is called Gosper's hack. It only works for n <= 32
because it uses the bits of an int
, but you can increase it to 64 if you use a long
.
int nextCombo(int x) {
// moves to the next combination with the same number of 1 bits
int u = x & (-x);
int v = u + x;
return v + (((v ^ x) / u) >> 2);
}
...
for (int x = (1 << k) - 1; (x >>> n) == 0; x = nextCombo(x)) {
System.out.println(Integer.toBinaryString(x));
}
For n = 5
and k = 3
, this prints
111
1011
1101
1110
10011
10101
10110
11001
11010
11100
exactly as you'd expect.