I'm making a rock-paper-scissors game, in which the computer picks a character 'r', 'p' or 's' randomly in each round. How can I do that?
char random_array[3] = {'r', 'p', 's'};
I'm making a rock-paper-scissors game, in which the computer picks a character 'r', 'p' or 's' randomly in each round. How can I do that?
char random_array[3] = {'r', 'p', 's'};
The simplest method is to to generate a random number between zero and the size of the array minus one. You can then use that number as an index for the array. Example using rand()
:
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(NULL)); // Seed the random number generator
char random_array[3] = {'r', 'p', 's'};
unsigned int randomIndex = rand() % 3; // Random number between 0 and 2
char randomCharacter = random_array[randomIndex];
};
If you want truly random values, then there are better alternatives than rand()
, but for a simple game it should work just fine.