posts - 183,  comments - 10,  trackbacks - 0

按一定概率打印数,不是随机数

打印的数是随机生成的,但是总体上看,不同的随机数打印出来的次数要不同。
打印 1000 个随机数,随机数的范围是 0-100,这 1000 个随机数根据其大小出现次数的比例不同,1 出现的比例最小,100 出现的比率最大。

需要注意的东西
随机数的范围 m
随机参数的依据,这里的依据是根据随机数的大小确定的,即使函数中的 t
产生的随机数的个数 n
保存的结果 a ,a 中保存的其实不是 rand 产生的数,而是根据 rand 产生的数进而确定的 t 的下标
统计结果的 s
这里用到了 rand 函数,a 中保存的不是直接取自 rand ,而是根据 rand 产生的数间接得到的 t 的那个下标,因为题目就是要求根据不同的概率打印出数,这个数其实不是随机数了。

实现:

 1 #include <iostream>
 2 #include <string>
 3 #include <ctime>
 4 #include <cstdlib>
 5 #include <cstring>
 6 using namespace std;
 7 
 8 // 结果存于 a 中,产生 n 个结果
 9 // 范围是从 1 - m
10 int foo(int a[], int s[], int n, int m)
11 {
12     int* t = new int [m];
13     t[0= 1;
14     for (int i = 1; i < m; ++i)
15     {
16         t[i] = t[i - 1+ i + 1;
17     }
18     int MAX = (1 + m) * m / 2;
19     
20     // cout << t[m - 1] << endl;
21     // cout << MAX << endl;
22     
23     srand(time(0));
24     int e = 0;
25     int r = 0;
26     for (int i = 0; i < n; ++i)
27     {
28         r = (rand() % MAX) + 1;
29         //cout << "r: " << r << endl;
30         for (int j = m - 1; j >= 0--j)
31         {
32             if (r > t[j])
33             {
34                 a[e++= j + 1 + 1;
35                 break;
36             }
37             else if (r == t[j])
38             {
39                 a[e++= j + 1;
40                 break;
41             }
42         }
43         /*
44         for (int j = 0; j < m; ++j)
45         {
46             if (r <= t[j])
47             {
48                 //cout << j + 1 << endl;
49                 a[e++] = j + 1;
50                 break;
51             }
52         }
53         */
54     }
55     
56     memset(s, 0sizeof (*s) * m);
57     for (int i = 0; i != n; ++i)
58     {
59         ++s[a[i] - 1];
60     }
61 }
62 
63 int main()
64 {
65     int n = 0, m = 0;
66     int* a, * s;
67     while (cin >> n >> m)
68     {
69         a = new int [n];
70         s = new int [m];
71         foo(a, s, n, m);
72         
73         for (int i = 0; i < n; ++i)
74         {
75             cout << a[i] << ' ';
76         }
77         cout << endl;
78         
79         for (int i = 0; i != m; ++i)
80         {
81             cout << i + 1 << "" << s[i] << endl;
82         }
83     }
84     return 0;
85 }


posted on 2011-07-19 14:20 unixfy 阅读(177) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理