Problem
Given a number x, less than 100. How will you generate true with probability x/100.
So if x = 65, how will you generate true with probability 65/100.
You can represent true by 1 and false by 0.
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Generate true or false with given probability
Created Data : 17-07-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
using namespace std;
bool GenerateProbility(int x)
{
return (x < (rand() % 100)) ? true : false;
}
int main(int argc, char* argv[])
{
for(int i = 0; i < 100; ++ i){
cout << setw(3) << i;
cout << setw(3) << GenerateProbility(i) << endl;
}
return 0;
}
Output
0 1
1 1
2 1
3 0
4 1
5 1
6 1
7 1
8 1
9 1
10 0
11 1
12 1
13 1
14 1
15 1
16 1
17 1
18 1
19 1
20 1
21 0
22 0
23 1
24 1
25 1
26 0
27 0
28 0
29 1
30 1
31 0
32 1
33 1
34 1
35 0
36 1
37 1
38 0
39 1
40 0
41 0
42 0
43 0
44 1
45 1
46 0
47 0
48 1
49 1
50 0
51 0
52 1
53 1
54 0
55 1
56 0
57 0
58 0
59 1
60 0
61 0
62 1
63 0
64 1
65 0
66 0
67 0
68 0
69 0
70 0
71 0
72 1
73 0
74 0
75 0
76 0
77 0
78 1
79 0
80 0
81 0
82 1
83 0
84 0
85 0
86 0
87 0
88 0
89 0
90 0
91 0
92 0
93 0
94 0
95 0
96 0
97 0
98 0
99 0
Press any key to continue . . .