Consider the entire combination of length 3 of the next array of integer {1,2,3}.
I would like to go through the entire combination of length 3 using the following algorithm from wikipedia
// find next k-combination bool next_combination(unsigned long& x) // assume x has form x'01^a10^b in binary { unsigned long u = x & -x; // extract rightmost bit 1; u = 0'00^a10^b unsigned long v = u + x; // set last non-trailing bit 0, and clear to the right; v=x'10^a00^b if (v==0) // then overflow in v, or x==0 return false; // signal that next k-combination cannot be represented x = v +(((v^x)/u)>>2); // v^x = 0'11^a10^b, (v^x)/u = 0'0^b1^{a+2}, and x ← x'100^b1^a return true; // successful completion }
What should be my initial value for this algorithm for all combinations {1,2,3}? When I get the result of the algorithm, how can I restore the combination?
I tried the following direct adaptation, but I am new to bitwise arithmetic, and I cannot say if this is correct.
// find next k-combination, Java int next_combination(int x) { int u = x & -x; int v = u + x; if (v==0) return v; x = v +(((v^x)/u)>>2); return x; }
user1030312
source share