I need to generate a random number, but a better chance at generating a particular one.
For example:
I would like to generate 0, 90% of the time,
and 1 10% of the time.
I know it has something to do with:
rand() % 2 and all that, but I'm stuck.
For your particular example:
unsigned n=(rand()%10<9);
Note: rand()%10's distribution is not completely flat. Depending on RAND_MAX, the first few values are slightly more likely.
Last edited on
Ok how about this?
I'm writing a function:
I would like to:
return 1 35% of the time
return 2 32% of the time
return 3 33% of the time.
How would I achieve this?
How about somthing like (rand / RAND_MAX) * 100, to get a percentage and then retun the relavant number based on that. (if num <35 return 1...)
Thank you Grey Wolf.
This is off the top of my head:
1 2 3 4 5 6 7 8 9 10 11 12
|
int randomPercent;
srand( time(NULL) );
randomPercent = ( ( rand() ) / RAND_MAX ) * 100;
if( randomPercent <= 35 )
return 1;
else if( randomPercent <= 67 && randomPercent > 35 )
return 3;
else
return 2;
|
Last edited on
You will need to do the percentage calc as a double the convert it down to int.
You need to cast rand() to double, this will then d the division as a double giving a value between 0 and 1...