shuffle.c

来自「与C语言四书五经之《C和指针》的配套的书上源代码。」· C语言 代码 · 共 39 行

C
39
字号
/*
** Use random numbers to shuffle the "cards" in the deck.  The second
** argument indicates the number of cards.  The first time this
** function is called, srand is called to initialize the random
** number generator.
*/
#include <stdlib.h>
#include <time.h>
#define	TRUE	1
#define	FALSE	0

void shuffle( int *deck, int n_cards )
{
	int	i;
	static	int	first_time = TRUE;

	/*
	** Seed the random number generator with the current time
	** of day if we haven't done so yet.
	*/
	if( first_time ){
		first_time = FALSE;
		srand( (unsigned int)time( NULL ) );
	}

	/*
	** "Shuffle" by interchanging random pairs of cards.
	*/
	for( i = n_cards - 1; i > 0; i -= 1 ){
		int	where;
		int	temp;

		where = rand() % i;
		temp = deck[ where ];
		deck[ where ] = deck[ i ];
		deck[ i ] = temp;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?