Nidal
Nidal

Reputation: 1883

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 ?

Upvotes: 0

Views: 124

Answers (2)

TomF
TomF

Reputation: 183

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.

Upvotes: 2

NPE
NPE

Reputation: 500367

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.

Upvotes: 0

Related Questions