Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
please tell me how to randomize characters or words in C.
Example:
I will input R(red) Y(yellow) G(green) B(blue).
The computer will randomize it and it can also be duplicated.
for instance, it could be R R B G or G B B Y..

please tell me how.. I need it to make a game called MASTERMIND.

Help would be much appreciated. Thanks.
Posted
Comments
Sandeep Mewara 5-Sep-10 8:27am    
Try first!... you need to put some effort.

You may store the charachters in an array, e.g.
const char col[]={'R','Y','G','B'};


then use the rand function to select the index of the character:
int r = rand() % sizeof(col);

For instance:

int i;
for (i=0; i<4; i++)
{
  int r = rand() % sizeof(col);
  printf("%c ", col[r]);
}
printf("\n");


:)
 
Share this answer
 
Comments
Ryan Nair 5-Sep-10 11:25am    
Sir, I have tried you're suggestion. But everytime i'm running the program. The set of code is always the same:

My code is like this:

const char col[]={'R','Y','BG','B','P','G'}; /*in the declaration area*/

for(i=0;i<6;i++) //IN THE
{
int r=rand()%sizeof(col); MAIN
printf("%c ",col[r]);
}
printf("
"); AREA//


THE OUTPUT IS ALWAYS: P P B P P Y

How to randomize it every time I would run the program?
Hope you can answer me back. Thanks.
CPallini 5-Sep-10 12:10pm    
To generate a different sequence every time your application runs, you have to call first 'srand( (unsigned)time( NULL ) );', see the example at the MSDN page http://msdn.microsoft.com/en-us/library/398ax69y%28VS.71%29.aspx
Try here:
random numbers c[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900