0

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'};

  • 1
    Does this answer your question? [How to generate a random number in C++?](https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c) – Retired Ninja Nov 21 '21 at 14:11
  • https://en.cppreference.com/w/cpp/algorithm/sample – m88 Nov 21 '21 at 14:11

1 Answers1

0

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.

JensB
  • 839
  • 4
  • 19
  • Just a minor caution: running this program several times in rapid succession will generate the same "random" character, because `time(NULL)` will return the same value when it's called more than once with little time between the calls. There's no way around that, and it's not an issue in programs that run longer than this one. +1. – Pete Becker Nov 21 '21 at 15:37
  • @PeteBecker Correct. Although a rock-paper-scissors game lasts long enough for that not to be an issue in this case, so I wouldn't worry about it if I was OP. – JensB Nov 21 '21 at 15:39