Created
June 14, 2012 17:35
-
-
Save josejuan/2931654 to your computer and use it in GitHub Desktop.
Combinaciones de N elementos tomados de M en M.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Todas las combinaciones de N elementos | |
void Combinaciones( int N ) { | |
for( int n = 0; n < 1 << N; n++ ) { | |
// Usar combinación. | |
} | |
} | |
// Combinaciones de N elementos tomados de M en M | |
void Combinaciones( int N, int M ) { | |
for( int n = 0; n < 1 << N; n++ ) { | |
// Tomada de http://graphics.stanford.edu/~seander/bithacks.html | |
// Cuenta el número de bits a 1 (sólo para 32 bits) | |
int v = n - ( ( n >> 1 ) & 0x55555555 ); | |
v = ( v & 0x33333333 ) + ( ( v >> 2 ) & 0x33333333 ); | |
v = ( ( v + ( v >> 4 ) & 0xF0F0F0F ) * 0x1010101 ) >> 24; | |
if( v == M ) { | |
// Usar combinación. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment