按一定概率打印數,不是隨機數
打印的數是隨機生成的,但是總體上看,不同的隨機數打印出來的次數要不同。
打印 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, 0, sizeof (*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 閱讀(186)
評論(0) 編輯 收藏 引用