c++ - Generating random numbers with certain probability -


this question has answer here:

i want generate 10 random numbers in c++ between 1 , 3 inside loop such 1 comes times (say 50% times), 2 (30% times) , 3(20% times). possible so?

i have made following code random numbers between 1 , 3 how add probabilities?

#include <iostream> #include <windows.h> #include "time.h" int main(int argc, char*argv[]) {     srand ( time(null) );     (int t = 0; t < 10; t++)     {         int random_x;          random_x = rand() % 3+1;         std::cout << "\nrandom x = " << random_x << std::endl;     }     sleep(50000);     return 0; } 

you can (in pseudo code)

x=random(0,100) if(x<p1){   y=1; } else if (x<p2)   y=2 } else{   y=3 } 

p1 change 1
p2-p1 change 2
, 100-p2 change 3


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -