Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C Game TurboC
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 5-Sep-10 3:21am
Comments
Sandeep Mewara at 5-Sep-10 8:27am
   
Try first!... you need to put some effort.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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");
 
Smile | :)
  Permalink  
Comments
Ryan Nair at 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 at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Try here:
random numbers c[^]
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 290
1 Jochen Arndt 165
2 DamithSL 125
3 PIEBALDconsult 110
4 Garth J Lancaster 90
0 OriginalGriff 5,790
1 DamithSL 4,601
2 Maciej Los 4,012
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,195


Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 5 Sep 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100