怎样将数据分组呢
将1、2、3、4、5、6、7、8、9九个数字分成三组,每个数字只能用一次,即每组三个数不许有重复数字,也不许同其它组的三个数字重复。我希望能把分组结果输出来,但完全没思路。我新学,请多指教。
#include <stdio.h> #include <string.h> #include <stdbool.h> static 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 = 9; const size_t m = 3; unsigned cnt = 0; unsigned a[] = { 1,2,3,4,5,6,7,8,9 }; 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; }