问题描述:一个色子有六(N)面,每面出现是等概率的。现使用该色子随机表示M个等概率事件。

 

  1. #include <stdio.h>     
  2. #include <stdarg.h>     
  3. #include <stdlib.h>     
  4. #include <dirent.h>     
  5. #include <sys/stat.h>     
  6. #include <string.h>     
  7. #include <time.h>     
  8.     
  9. #define EVENT_MAX       100     
  10.     
  11. static int dice_radix; /* 基数,比如7件事色子有6面,则基数为9 */    
  12. static int event_count; /* 事件数目,比如这里的7、4、5、8、9、10 */    
  13. static int throw_times; /* 所需要掷色子次数,比如此题事件7次则需要掷2次 */    
  14. static int dice_max; /* 色子的面数,比如6 */    
  15.     
  16. int init_rand(int event_count, int dice_max_count);    
  17. int get_rand(void);    
  18.     
  19. int main(int argc, char *argv[])    
  20. {    
  21.     int i;    
  22.     int ret[EVENT_MAX];    
  23.     memset(ret, 0, sizeof(ret));    
  24.     init_rand(7, 6);    
  25.     printf("%d, %d, %d, %d...\n", dice_radix, event_count, throw_times, dice_max);    
  26.     for(i=0; i<10000; ++i) {    
  27.         ret[get_rand()]++;    
  28.     }    
  29.     int total = 0;    
  30.     for(i=0; i<event_count; ++i) {    
  31.         total += ret[i];    
  32.         printf("event[%2d]=%4d...\n", i, ret[i]);    
  33.     }    
  34.     printf("\ntotal=%d...\n", total);    
  35.     return 0;    
  36. }    
  37.     
  38. static time_t rand_pip;    
  39. int init_rand(int count, int dice_max_count)    
  40. {    
  41.     dice_radix = dice_max_count;    
  42.     event_count = count;    
  43.     throw_times = 1;    
  44.     dice_max = dice_max_count;    
  45.     if(count<=0) {    
  46.         return -1;    
  47.     }    
  48.     while(dice_radix < count) {    
  49.         ++throw_times;    
  50.         dice_radix *= dice_max_count;    
  51.     }    
  52.     while(dice_radix%count!=0) {    
  53.         ++count;    
  54.     }    
  55.     dice_radix = count;    
  56.     rand_pip = time(NULL);    
  57.     return 0;    
  58. }    
  59.     
  60. int get_rand(void)    
  61. {    
  62.     int ret;    
  63.     int i;    
  64.     do {    
  65.         rand_pip += 100;    
  66.         srand(rand_pip);    
  67.         ret = 0;    
  68.         for(i=0; i<throw_times; ++i) {    
  69.             ret *= dice_max;    
  70.             ret += rand()%dice_max;    
  71.         }    
  72.         ret = rand()%dice_radix;    
  73.     } while(ret>=event_count);    
  74.     return ret;    
  75. }    

运行结果:
 

  1. 9, 7, 2, 6...    
  2. event[ 0]=1450...    
  3. event[ 1]=1433...    
  4. event[ 2]=1456...    
  5. event[ 3]=1397...    
  6. event[ 4]=1472...    
  7. event[ 5]=1408...    
  8. event[ 6]=1384...    
  9.     
  10. total=10000...