When I read some question to write random nuber generator ,I saw that function and it efficient but it is written in C#. I want see that function in form of c language,can anyone help?
IEnumerable<int> ForLargeQuantityAndRange开发者_Python百科(int quantity, int range)
{
for (int n = 0; n < quantity; n++)
{
int r = Random(range);
while (!used.Add(r))
r = Random(range);
yield return r;
}
}
Questions regarding number generators for C have been asked before here on SO, such as in the article "Create Random Number Sequence with No Repeats".
I'd suggest looking at the above article to see if anything is suitable and provides a useful alternative to the standard rand() function in C, assuming that you've already looked at the latter and rejected it.
This is not quite a function, as function in C or C++. This is a co-routine, which may be resumed.
To implement it in C, you will need to maintain external state, and provide a "next value" func.
The advantage of this function is that it guarantees unique values. Do you really need it? If not, use stdlib's rand, multiplied by proper factors.
Do you just want random numbers? If so, why don't you use one of the many libraries out there that can do it for you in a cross platform fashion? Here's one.
To write a co-routine in C, you need to maintain state. This simplest way to do this is to use a static
variable. For this example, it would look something like:
int ForLargeQuantityAndRange(int init_quantity, int init_range)
{
static int n;
static int quantity, range;
if (init_quantity > 0)
{
n = 0;
quantity = init_quantity;
range = init_range;
}
if (n++ < quantity)
{
int r = Random(range);
while (!used_add(r))
r = Random(range);
return r;
}
/* Quantity exceeded */
return -1;
}
...where you would call it with (quantity, range)
to intialise a new sequence, and (0, 0)
to continue the previous sequence.
Note that you will have to supply implementations of the Random()
and used_add()
functions.
精彩评论