This code is used to get random numbers with a certain probability:
8 is returned if r
is between 0 and 0.8; 2 is returned if r
is between 0.8 and 1.
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
int main()
{
srand(time(NULL));
double r = rand() / (double)RAND_MAX;
double sum = 8 + 2;
if (r < 8 / sum) {
printf("80% \n");
} else {
printf("20% \n");
}
}
but if I have more than two numbers, say n, how can I handle it? Can I handle it with multiple if-else statements? Or what else?
Simple
O(n)
timeO(n)
time:
Complex
O(n)
time (this array should have increasing values)>=
the random number, in O(log(n))
time.I have not included the necessary corner cases to address. I am sure you can do it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With