-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedium_Prob152.cpp
More file actions
54 lines (43 loc) · 1.17 KB
/
Medium_Prob152.cpp
File metadata and controls
54 lines (43 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* You are given n numbers as well as n probabilities that sum up to 1.
Write a function to generate one of the numbers with its corresponding probability.*/
#include <iostream>
#include <vector>
using namespace std;
void generateAccordingNumber(vector<float>& probability, vector<float>& numbers)
{
int n = numbers.size();
// Random generator
srand(time(0));
float random = (float)(rand()) / (float)(RAND_MAX);
float bornInf = 0;
float bornSup = probability[0];
bool notFind = true;
int iterator = 0;
while(notFind)
{
cout << "R " << random << " B+ " << bornSup << " i " << iterator << endl;
if (random > bornSup)
{
iterator += 1;
if (iterator + 1 == n)
{
bornSup = 1;
}
else
{
bornSup += probability[iterator];
}
}
else
{
notFind = false;
}
}
cout << numbers[iterator] << endl;
}
int main(int argc, char *argv[])
{
vector<float> list = {5,4,3,2,1};
vector<float> proba = {0.05,0.2,0.2,0.1,0.45};
generateAccordingNumber(proba, list);
}