关于数据分组问题
我想将15个数据三个一组分组,要分出所有情况,让每次都不一样。突然想不出怎么办。
#include <stdio.h> #include <string.h> #include <stdbool.h> unsigned mask_next( unsigned mask[], unsigned val ) { size_t r; for( r=val; mask[r]==0; ++r ); mask[r] = 0; return r; } bool next( size_t n, size_t m, unsigned a[] ) { for( size_t i=n-1-m; i!=0; --i, i-=(i!=0 && i%m==0) ) { if( a[i] < a[i/m*m+2*m-1] ) { size_t t = i/m*m+2*m-1; for( size_t j=i/m*m+m; j!=n; ++j ) if( a[j]>a[i] && a[j]<a[t] ) t = j; unsigned tmp = a[i]; a[i] = a[t]; a[t] = tmp; if( i < n-m-1 ) { unsigned mask[n]; memset( mask, 0, n*sizeof(mask[0]) ); for( size_t j=i+1; j!=n; ++j ) mask[a[j]] = 1; for( size_t j=i+1; j!=i/m*m+m; ++j ) a[j] = mask_next( mask, a[i] ); for( size_t j=i/m*m+m; j!=n; ++j ) a[j] = mask_next( mask, 0 ); } return true; } } return false; } int main( void ) { const size_t n = 15; const size_t m = 3; unsigned cnt = 0; unsigned a[15] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 }; for( bool b=true; b; b=next(n,m,a) ) { //for( size_t i=0; i!=n; ++i ) // printf( "%u%s", a[i], i+1==n?"\n":(", "+((i+1)%m!=0)) ); ++cnt; } printf( "--- %u ---\n", cnt ); return 0; }