## Get random numbers!!!

Unregistered

Post: #1
"Hello" people!!
Sorry This simple question....!!!!!!!

How can i get a random number betwen a set off them???
For example: a random number betwen (0, 90, -90 and 180)...

I use rand()%?? but only work with consecutive numbers!!! right?

Anyone? Thanks!!!!
Moderator
Posts: 529
Joined: 2003.03
Post: #2
Are you saying you want it to randomly pick a number between -90 and 180, or that you want it to pick a number randomly that is one of those 4 numbers?

"Yes, well, that's the sort of blinkered, Philistine pig-ignorance I've come to expect from you non-creative garbage."
Unregistered

Post: #3
One of those 4 numbers...
Moderator
Posts: 529
Joined: 2003.03
Post: #4
OK. In this case, generate a random int between 0 and 3. Multiply the result by 90. Then subtract 90.

"Yes, well, that's the sort of blinkered, Philistine pig-ignorance I've come to expect from you non-creative garbage."
Sage
Posts: 1,199
Joined: 2004.10
Post: #5
Or, in a more general case, generate a random int, and modulo it by N, where N Is the size of your set. Then, take the corresponding value in the set.

Code:
const int mySetSize = 4;
int mySet[] = { 0, -90, 90, 180 };

int v = mySet[ random() % mySetSize ];
Unregistered

Post: #6
thanks all....
Tobi
Unregistered

Post: #7
And don't forget to set the random seed at application startup or you'll get the same numbers all the time. Use srand(time()); to do this. Still the numbers you'll get with rand() are not very random, you might want to try RANROT instead. There's some FAQ about random numbers on idevgames I think
Moderator
Posts: 365
Joined: 2002.04
Post: #8
The thing to watch out for with rand() is that it's generally extremely non-random in its lowest bits. For example, if you keep doing 'rand() % 2', you'll get an alternating series of 0, 1, 0, 1 with a typical implementation. rand() % 4 isn't going to be much better.

The simplest way to avoid this if you don't want to use a different random number generator is to shift the bits of the result right a few places. That is, do (rand() >> 8) % 4. You're much less likely to get an obviously cyclic sequence that way.

Neil Carter
Nether - Mac games and comic art