Get random numbers!!!
"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!!!!
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!!!!
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."
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."
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 ];
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
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.
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.
Possibly Related Threads...
Thread: | Author | Replies: | Views: | Last Post | |
Random numbers | Damian | 11 | 4,676 |
Jul 14, 2003 07:30 AM Last Post: aaronsullivan |