Reputation: 141
Im making a small C program to resemble the game code breaker or Mastermind. This is my code so far. As of now all it does is generate a "random" code and print the array of the code.. Every time I compile it, it generates the same array of 2,2,6,3. Can anyone help me have a truly random number generator?
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define CODELENGTH 4
#define NUMSYMBOLS 6
const int LOW = 1;
const int HIGH = 6;
void genCode (int MasterCode[])
{
int i=0;
int k;
while (i < 4){
MasterCode[i] =rand() %(HIGH-LOW+1)+LOW;
i++;
}//end while loop.
for ( k = 0 ; k < 4; k++ ) {
printf( "%d ", MasterCode[ k ] );
}
printf( "\n" );
}
void getGuess (int guess[])
{
int b[ 4 ];
int number = 0;
printf( "Please enter your list of 4 numbers between 1 and 6: " );
int j;
int k;
for ( j = 0 ; j < 4; j++ ) {
scanf( "%d", &number );
b[ j ] = number;
}
printf( "Your array has these values: " );
for ( k = 0 ; k < 4; k++ ) {
printf( "%d ", b[ k ] );
}
printf( "\n" );
}
int main (int argc, char **argv)
{
int MasterCode[4];
genCode(MasterCode);
}
Upvotes: 3
Views: 572
Reputation: 21
Truly random generators are expensive.
The rand() functions generates a sequence that appears to be random, but its always the same.
The line
srand(time(NULL));
will only initialize this to a certain value that will most likely be different every time, which will give you what you want.
For a game, this will probably be enough. If you need to go further than that and have a more random sequence, you can try to generate something based on user input, like the timing of keystrokes, mouse movement and time.
That's about as close as you will get without specialized hardware.
Upvotes: 1
Reputation: 141
What I did was removed the equation I originally had for the range switched it to something more simpler then I added the seed generator in main.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define CODELENGTH 4
#define NUMSYMBOLS 6
void genCode (int MasterCode[])
{
int i=0;
int k;
while (i < 4){
MasterCode[i] =rand() %6 +1;
i++;
}//end while loop.
for ( k = 0 ; k < 4; k++ ) {
printf( "%d ", MasterCode[ k ] );
}
printf( "\n" );
}
void getGuess (int guess[])
{
int b[ 4 ];
int number = 0;
printf( "Please enter your list of 4 numbers between 1 and 6: " );
int j;
int k;
for ( j = 0 ; j < 4; j++ ) {
scanf( "%d", &number );
b[ j ] = number;
}
printf( "Your array has these values: " );
for ( k = 0 ; k < 4; k++ ) {
printf( "%d ", b[ k ] );
}
printf( "\n" );
}
int main (int argc, char **argv)
{
srand ( time(NULL) );
int MasterCode[4];
genCode(MasterCode);
}
Upvotes: 0
Reputation: 28302
You need to seed the random number generator before using rand()
. This is usually done as:
srand(time(NULL));
More information available here.
Upvotes: 7