Hello,
I need to random generate some values in c++. I know that I can use rand() but I need to generate values with the following condition: the generated values must be equal to 2^n (0, 2, 4, 8, ...). Is that possible?
Kind regards,
M.
Hello,
I need to random generate some values in c++. I know that I can use rand() but I need to generate values with the following condition: the generated values must be equal to 2^n (0, 2, 4, 8, ...). Is that possible?
Kind regards,
M.
You could populate a vector with the values you deem valid and std::random_shuffle
that vector. At that point you could just iterate over the shuffled vector to get random values.
First: seed you random number generator once with srand(time(NULL))
.
Then, get a value between 0 and 31 using the modulus operator on the result of rand(), as so rand() % 32
. That gives you "n".
Finally, use the bitshift operator to raise to the power of "n". As so 1 << n
.
And, that's it. Enjoy!
To get a random int between 0 and 31 (inclusive) using rand(), prefer something like int( 32.0 * ( rand() / (RAND_MAX+1.0) ) ) ;
Or else, you would be assuming that the least significant 5 bits of the pseudo random number generated by rand() are also randomly distributed.