#include <iostream>
using namespace std;
void display(int* tab, int k)
{
for(int i = 0; i < k; ++i)
{
cout << tab[i] << ",";
}
cout << endl;
}
unsigned int GetBitPositionByNr(int n, int k)
{
if (k <= 0 || n <= 0) return 0;
unsigned int f = 0, i = 0;
while ((1 << i) <= n)
{
if (n & (1 << i))
f++;
i++;
if (f==k) return i;
}
return -1;
}
unsigned int Combination_n_of_k(int n, int k)
{
if (k > n) return 0;
if (k == 0 || k == n) return 1;
if (k * 2 > n) k = n - k;
unsigned int r = 1;
for (int d = 1; d <= k; ++d)
{
r *= n--;
r /= d;
}
return r;
}
int main() {
// your code goes here
int n = 4;
int k = 2;
int combination = (1 << k) - 1;
int new_combination = 0;
int change = 0;
while (false)
{
// return next combination
cout << combination << endl;
// find first index to update
int indexToUpdate = k;
while (indexToUpdate > 0 && GetBitPositionByNr(combination, indexToUpdate)>= n - k + indexToUpdate)
indexToUpdate--;
if (indexToUpdate == 1) change = 1; // move all bites to the left by one position
if (indexToUpdate <= 0) break; // done
// update combination indices
new_combination = 0;
for (int combIndex = GetBitPositionByNr(combination, indexToUpdate) - 1; indexToUpdate <= k; indexToUpdate++, combIndex++)
{
if(change)
{
new_combination |= (1 << (combIndex + 1));
}
else
{
combination = combination & (~(1 << combIndex));
combination |= (1 << (combIndex + 1));
}
}
if(change) combination = new_combination;
change = 0;
}
int final = 0;
for(int i = n - 1; i >= k; --i) final += (1 << i);
cout << "Final " << final << endl;
unsigned int v = (1 << k) - 1; // current permutation of bits
unsigned int w = 0; // next permutation of bits
do
{
unsigned int t = (v | (v - 1)) + 1;
w = t | ((((t & -t) / (v & -v)) >> 1) - 1);
v = w;
cout << "comb bit: " << v << endl;
} while(w != final)
return 0;
}