简体   繁体   中英

rand() function in with probability in chossing IP's

Hi I'm working on a project in c

I have 3 IPs and every IP has a weight, I want to return the IP's according to its weights using the random function,,,, for example if we have 3 IP's : X with weight 6,Y with weight 4 and Z with weight 2, I want to return X in 50% of cases and Y in 33% of cases and Z in 17% of cases, depending on random function in C.

could any one help me with this please ?

Get a random between 0 and 1000000 for example. Then check, if it's smaller then 500000 then choose x, if its between 500000 and 830000 choose y and if its between 830000 and 1000000 choose z.

double r = rand() / (double)RAND_MAX;
double denom = 6 + 4 + 2;
if (r < 6 / denom) {
  // choose X
} else if (r < (6 + 4) / denom) {
  // choose Y
} else {
  // choose Z
}

I've written it in a manner that should make it clear how to generalize the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM