Search code examples
c++randomsrand

C++ random number from a set


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.


Solution

  • Say these numbers are in a set of size 5, all you gotta do is find a random value multiplied by 5 (to make it equi probable). Assume the rand() method returns you a random value between range 0 to 1. Multiply the same by 5 and cast it to integer you will get equiprobable values between 0 and 4. Use that to fetch from the index.

    I dont know the syntax in C++. But this is how it should look

    my_rand_val = my_set[(int)(rand()*arr_size)]
    

    Here I assume rand() is a method that returns a value between 0 and 1.