问题描述:一个色子有六(N)面,每面出现是等概率的。现使用该色子随机表示M个等概率事件。
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include <time.h> #define EVENT_MAX 100 static int dice_radix; /* 基数,比如7件事色子有6面,则基数为9 */ static int event_count; /* 事件数目,比如这里的7、4、5、8、9、10 */ static int throw_times; /* 所需要掷色子次数,比如此题事件7次则需要掷2次 */ static int dice_max; /* 色子的面数,比如6 */ int init_rand(int event_count, int dice_max_count); int get_rand(void); int main(int argc, char *argv[]) { int i; int ret[EVENT_MAX]; memset(ret, 0, sizeof(ret)); init_rand(7, 6); printf("%d, %d, %d, %d...\n", dice_radix, event_count, throw_times, dice_max); for(i=0; i<10000; ++i) { ret[get_rand()]++; } int total = 0; for(i=0; i<event_count; ++i) { total += ret[i]; printf("event[%2d]=%4d...\n", i, ret[i]); } printf("\ntotal=%d...\n", total); return 0; } static time_t rand_pip; int init_rand(int count, int dice_max_count) { dice_radix = dice_max_count; event_count = count; throw_times = 1; dice_max = dice_max_count; if(count<=0) { return -1; } while(dice_radix < count) { ++throw_times; dice_radix *= dice_max_count; } while(dice_radix%count!=0) { ++count; } dice_radix = count; rand_pip = time(NULL); return 0; } int get_rand(void) { int ret; int i; do { rand_pip += 100; srand(rand_pip); ret = 0; for(i=0; i<throw_times; ++i) { ret *= dice_max; ret += rand()%dice_max; } ret = rand()%dice_radix; } while(ret>=event_count); return ret; }
运行结果:
9, 7, 2, 6... event[ 0]=1450... event[ 1]=1433... event[ 2]=1456... event[ 3]=1397... event[ 4]=1472... event[ 5]=1408... event[ 6]=1384... total=10000...