Fractale
Fractale

Reputation: 1644

How to get random value from assigned enum in c++?

I want a random color from this enum:

enum Color {
red = 10,
black = 3,
pink = 6,
rainbow=99    
};

Color my_randowm_color = ...

How can i do that?

Upvotes: 2

Views: 2870

Answers (4)

Daniel Langr
Daniel Langr

Reputation: 23497

Just for fun (-:

Color random_color() {
   int r = rand() % 4;
   return static_cast<Color>((r + 1) * 3 + (r >= 2) + (r >= 3) * 86);
}

Live demo: https://wandbox.org/permlink/j4YNMqWs41QJFeOB

Upvotes: 0

PapaDiHatti
PapaDiHatti

Reputation: 1921

You can create a array containing possible enums and then generate random number for array index starting from 0 to total possible enum values.

    #include <iostream>

    int main() 
    {
       enum Color {   red = 10, black = 3, pink = 6, rainbow=99 };
       int max = 3;
       int min = 0;

       srand(static_cast <unsigned int> (time(0)));
       int randNum = rand() % (max - min + 1) + min;

       Color forRandomPurpose[] = { red, black, pink, rainbow };
       Color my_random_color = forRandomPurpose[randNum];

       std::cout << "Hello World!\n";
       std::cout << my_random_color << std::endl;
    }

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66371

There is no way to enumerate the values of an enum.

You can use a table:

std::vector<int> colors = {red, black, pink, rainbow};

and then pick a random element from it.

Picking a random element left as an exercise.

Upvotes: 5

soda
soda

Reputation: 523

Note: This is a different approach based on my understanding of what the OP desires.

What you can do is generate a random number in a range of 0-3. As you have four colors. Then store your colors in an array. And use a function returning a random number as index of that array. In this manner You will get random colors among the ones you have.

eg.

random() {
// func definition
//  return random number in range of array indices
}

array = ["red","black","pink","rainbow"];

array[random()];

Upvotes: 0

Related Questions