in reply to Re: Odometer pattern iterator (in C).
in thread Odometer pattern iterator (in C). (Updated.)
Thanks to your having identified what I was after as "combinations of n things taken k at a time"; which just hadn't dawned on me, I went looking around in the guts of Algorithm::Combinatorics and translated his XS version of __next_combinations() to C, and arrived at:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include "..\C\mytypes.h" int nextCombination( U8 *tuple, int len_tuple, int max_n ) { int i, j; I32 offset = max_n - len_tuple; for( i = len_tuple; i >= 0; --i ) { I32 n = tuple[ i ]; if( n < i + offset ) { tuple[ i ] = ++n; for( j = i + 1; j <= len_tuple; ++j ) tuple[ j ] = ++n; return i; } } return -1; } void main( int argc, char **argv ) { U32 n = argc > 1 ? atoi( argv[ 1 ] ) : 5; U32 m = argc > 2 ? atoi( argv[ 2 ] ) : n>>1; U32 i, t = 1; U8 *tuple = malloc( m ); for( i = 0; i < m; ++i ) tuple[ i ] = i; for( i = 0; i < m; ++i ) printf( "%u ", tuple[ i ] ); printf( "\n" + ); while( nextCombination( tuple, m-1, n-1 ) >= 0 ) { for( i = 0; i < m; ++i ) printf( "%u ", tuple[ i ] ); printf( +"\n" ); ++t; } printf( "Iters:%I64u\n", t ); free( tuple ); return; }
Which works very nicely and very quickly.
|
---|