Tuesday, July 14, 2009

Help please?

all i need to do is get started its in the C++ language





Write a program that uses a random number generator to display one of 20 phrases stored in an array of char pointers. Let the user keep asking for phrases as long as desired

Help please?
Random Numbers





Random numbers are useful in programs that need to simulate random events, such as games, simulations and experimentations. In practice no functions produce truly random data -- they produce pseudo-random numbers. These are computed form a given formula (different generators use different formulae) and the number sequences they produce are repeatable. A seed is usually set from which the sequence is generated. Therefore is you set the same seed all the time the same set will be be computed.





One common technique to introduce further randomness into a random number generator is to use the time of the day to set the seed, as this will always be changing. (We will study the standard library time functions later in Chapter 20).





There are many (pseudo) random number functions in the standard library. They all operate on the same basic idea but generate different number sequences (based on different generator functions) over different number ranges.





The simplest set of functions is:





int rand(void);


void srand(unsigned int seed);





rand() returns successive pseudo-random numbers in the range from 0 to (2^15)-1.


srand() is used to set the seed. A simple example of using the time of the day to initiate a seed is via the call:





srand( (unsigned int) time( NULL ));





The following program card.c illustrates the use of these functions to simulate a pack of cards being shuffled:





/*


** 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 %26lt;stdlib.h%26gt;


#include %26lt;time.h%26gt;


#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 %26gt; 0; i -= 1 ){


int where;


int temp;





where = rand() % i;


temp = deck[ where ];


deck[ where ] = deck[ i ];


deck[ i ] = temp;


}


}


No comments:

Post a Comment