C++ random number from a set

user69514 picture user69514 · Mar 14, 2010 · Viewed 11.2k times · Source

Is it possible to print a random number in C++ from a set of numbers with ONE SINGLE statement?

Let's say the set is {2, 5, 22, 55, 332}

I looked up rand() but I doubt it's possible to do in a single statement.

Answer

Li0liQ picture Li0liQ · Mar 14, 2010
int numbers[] = { 2, 5, 22, 55, 332 };
int length = sizeof(numbers) / sizeof(int);
int randomNumber = numbers[rand() % length];