生成牌
# include <stdio.h>
# include <time.h>
# include <stdlib.h>
# define M 1
# define N 20
# define TOTAL_NUMS ( N - M + 1 )
int main ( ) {
int cards[ TOTAL_NUMS] ;
int i, j;
int id1, id2;
int swap_temp;
srand ( time ( NULL ) ) ;
for ( j = 1 ; j <= 20 ; j++ ) {
for ( i = 0 ; i < TOTAL_NUMS; i++ ) {
cards[ i] = M + i;
}
for ( i = 0 ; i < TOTAL_NUMS; i++ ) {
id1 = rand ( ) % ( TOTAL_NUMS) ;
id2 = rand ( ) % ( TOTAL_NUMS) ;
swap_temp = cards[ id1] ;
cards[ id1] = cards[ id2] ;
cards[ id2] = swap_temp;
}
printf ( "第%02d副牌:" , j) ;
for ( i = 0 ; i < TOTAL_NUMS; i++ ) {
printf ( "%3d" , cards[ i] ) ;
}
printf ( "\n" ) ;
}
getchar ( ) ;
}
生成牌结果
洗牌算法
# include <time.h>
# include <stdlib.h>
# include <stdio.h>
# define NUM 10
void swapInt ( int * a, int * b) ;
void knuthShuffle ( int a[ ] , int n, int b[ ] [ NUM] ) ;
void swapInt ( int * a, int * b) {
int t;
t = * a;
* a = * b;
* b = t;
}
void knuthShuffle ( int a[ ] , int n, int b[ ] [ NUM] ) {
int i;
for ( i = n - 1 ; i >= 1 ; i-- ) {
swapInt ( & a[ i] , & a[ rand ( ) % ( i + 1 ) ] ) ;
}
for ( i = 0 ; i < n; i++ ) {
b[ a[ i] - 1 ] [ i] ++ ;
}
}
int main ( ) {
int i, j, sum, a[ NUM] , b[ NUM] [ NUM] = { 0 } ;
srand ( time ( NULL ) ) ;
for ( i = 0 ; i < NUM; i++ ) {
a[ i] = i + 1 ;
}
for ( j = 0 ; j < 10000 ; j++ ) {
knuthShuffle ( a, NUM, b) ;
}
printf ( "牌面" ) ;
for ( i = 0 ; i < NUM; i++ ) {
printf ( " 位置%02d次数" , i + 1 ) ;
}
printf ( " 总次数" ) ;
printf ( "\n" ) ;
for ( i = 0 ; i < NUM; i++ ) {
printf ( " %02d " , i + 1 ) ;
for ( j = 0 , sum = 0 ; j < NUM; j++ ) {
if ( b[ i] [ j] > 0 ) {
printf ( "%8d " , b[ i] [ j] ) ;
sum += b[ i] [ j] ;
}
}
printf ( "%7d" , sum) ;
printf ( "\n" ) ;
}
getchar ( ) ;
}
洗牌结果