0

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 ?

Nidal
  • 1,717
  • 1
  • 27
  • 42

2 Answers2

2

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.

TomF
  • 183
  • 11
0
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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Isn't using larger values advised? I fear that in a small range the probability for the values will not be equal, am i wrong? – TomF Aug 22 '13 at 21:22
  • 2
    You are wrong. The size of the values involved does not affect the results in this function. –  Aug 22 '13 at 21:23
  • In theory, but any one way function you use, (give it inputs from MIN to MAX), and you will see that not all values are reached, and there is usually a lot more values around the middle of the range. now i don't know how rand is implemented but what makes you so sure that their probability is the same? – TomF Aug 22 '13 at 21:54
  • @TomF: I don't know why you'd think that. Where do one way functions come in? And why wouldn't all values be reached? What would cause a bias towards the middle of the range? – user2357112 Aug 22 '13 at 22:06
  • What is RAND_MAX means? – Nidal Aug 22 '13 at 22:10
  • Sidenote: RAND_MAX is guaranteed by POSIX (?) to be _at least_ 32K. – wildplasser Aug 22 '13 at 22:13
  • I have tried it and it keeps go to the third section "choose z", I think that the rand() function always returns the same value over and over why ??? and how can I get over this ?? – Nidal Aug 22 '13 at 22:27
  • @user2683768: Edit your question to show the code you are using. You are probably making a simple mistake like not calling `srand` or using `srand` incorrectly. – Blastfurnace Aug 22 '13 at 23:59
  • http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range-c The answer there explains preetty much what i meant. – TomF Aug 23 '13 at 04:08