信不信由你,您可以使用单个随机数进行这样的订单统计。如果k
是随机值的数量并且每个都在范围内1..max_value
,则:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main(void)
{
int seed;
/*
* Grab a seed value from /dev/random to avoid time dependency
* artifacts in the first generated rand() value when running
* this multiple times in quick succession.
*/
FILE *fp = fopen("/dev/random", "r");
fread((char*)(&seed),sizeof(seed),1,fp);
fclose(fp);
srand(seed);
int k = 20;
int max_value = 20;
/*
* The k'th root of a single uniform has the same distribution as
* the max of k uniforms. Then use inversion to convert to desired
* output range.
*/
int num = 1 + max_value * exp( log( ((double)rand()) / RAND_MAX ) / k );
printf("%d is the max of %d samples in the range 1..%d\n", num, k, max_value);
return 0;
}
与 1..20 范围内的最大 20 个随机数具有相同的分布,无需循环!取决于k
你的功能有多大和有多昂贵rand()
,这真的可以得到回报。