|
-
July 18th, 2005, 10:34 AM
#6
Re: random number generator
 Originally Posted by paskari
does anyone know a random number generator in C which bounds the return value between upper and lower, and ensures a unique return value each time
I basically want to randomly assign numbers from 1 to n but I never want to aply the same number twice.
Thanks
You can't simply use rand() for this. It's possible for rand() to return the same number twice. Even the code you posted in your second post can return a given number twice. What you need is an array of possible values. Let's say you have an array of n elements:
[e0, e1, e2, ... , e(n-2), e(n-1)]
Initial values will be (1+ the element indices):
[1,2,3,..., n-1, n]
Then you choose a random number between 0 and (n-1). Suppose you get
2. Then you will return 3 (because element 2 holds the value 3). But you need to make sure you don't use that number again. So what you do is copy the last element to element 2. Now you have:
[1,2,n,...,n-1, n]
The last element is in red because you don't need it anymore and can effectively treat it as no longer part of your array. For your next number, you choose a random number between 0 and (n-2). Even if the random generator returns 2 again, you'll have a unique number to return.
Anyway, I hope you get the idea. I'll leave the coding as an exercise for the reader.
- Kevin
P.S. log() and ceil() are expensive functions. It's usually sufficient to do the following (especially if you are using rand(), which if you read the FAQs is usually a poor random number generator anyway):
Code:
/* return a random integer between 1 and N */
int ranged_rand(int N)
{
return 1+(int)((rand()*1.0/RAND_MAX)*N);
}
Kevin Hall
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|