Skip to content

Instantly share code, notes, and snippets.

@yllan
Created April 17, 2012 02:58
Show Gist options
  • Select an option

  • Save yllan/2403086 to your computer and use it in GitHub Desktop.

Select an option

Save yllan/2403086 to your computer and use it in GitHub Desktop.
Bitwise Combination
#include<stdio.h>
void print_binary(long x, int digit)
{
for (int i = 1 << (digit - 1); i; printf("%d", !!(x & i)), i >>= 1);
puts("");
}
long next(long x)
{
long b = x & -x;
long t = x + b;
long c = x ^ t;
long m = (c >> 2) / b;
return t | m;
}
int main()
{
long c = 0, n = 6, k = 3;
for (c = (1 << k) - 1; c < (1 << n); c = next(c)) print_binary(c, n);
return 0;
}
/*
Output:
000111
001011
001101
001110
010011
010101
010110
011001
011010
011100
100011
100101
100110
101001
101010
101100
110001
110010
110100
111000
Algorithm:
http://realtimecollisiondetection.net/blog/?p=78
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment