信じられないかもしれませんが、このような注文統計を 1 つの乱数で行うことができます。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()
、これは本当に効果があります。