You should call srand()
before calling rand to initialize the random number generator.
Either call it with a specific seed, and you will always get the same pseudo-random sequence
#include <stdlib.h>
int main ()
{
srand ( 123 );
int random_number = rand();
return 0;
}
or call it with a changing sources, ie the time function
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
int random_number = rand();
return 0;
}
In response to Moon's Comment
rand() generates a random number with an equal probability between 0 and RAND_MAX (a macro pre-defined in stdlib.h)
You can then map this value to a smaller range, e.g.
int random_value = rand(); //between 0 and RAND_MAX
//you can mod the result
int N = 33;
int rand_capped = random_value % N; //between 0 and 32
int S = 50;
int rand_range = rand_capped + S; //between 50 and 82
//you can convert it to a float
float unit_random = random_value / (float) RAND_MAX; //between 0 and 1 (floating point)
This might be sufficient for most uses, but its worth pointing out that in the first case using the mod operator introduces a slight bias if N does not divide evenly into RAND_MAX+1
.
Random number generators are interesting and complex, it is widely said that the rand() generator in the C standard library is not a great quality random number generator, read (http://en.wikipedia.org/wiki/Random_number_generation for a definition of quality).
http://en.wikipedia.org/wiki/Mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html ) is a popular high quality random number generator.
Also, I am not aware of arc4rand() or random() so I cannot comment.
Best Answer
Throw that code away, seriously. You need a shuffling algorithm, not a piece of code that checks older values for duplicates. Doing it your way will end up taking longer and longer as your pool runs out. The advantage of a shuffling algorithm is that it doesn't degrade as the pool becomes smaller.
Here's a piece of code I used in answering a different question. It maintains a list of numbers and, when it returns a random one to you, it removes it from the list and decrements the count for the next random selection.
A sample output shows it in action:
Call it with a non-negative pool size and it sets up a new sequence and returns the first random value. Following that, you can call it with
-1
and it will get the next random, unique number from the pool. When the pool is exhausted, it will return -1.The other answer that contained this code has a version that can maintain multiple pools as well if you want to be able to use this function in threaded code.