1

Let's say I have an array probabilities = [0.1, 0.2, ..., 0.1, 0.4] of n elements. These are floating point values, not integer weights.

How do I extract a random integer from 1 to n with the given probabilities in Ansi C?

probabilities = [0.1, 0.2, 0.1, 0.15, 0.05, 0.1, 0.4]
extract_random_integer(probabilities)
Luca Cappelletti
  • 2,485
  • 20
  • 35
  • @Blaze hesitant at that. The accepted answer is somewhat adaptable but clearly all other answers there are very much C++ only. – Antti Haapala -- Слава Україні Jun 19 '19 at 12:58
  • @Blaze in particular there it works since the weights are integers, these are floats. – Luca Cappelletti Jun 19 '19 at 12:59
  • Surely you can tweak the code so that it works with floats. The type of the weights really doesn't matter. In any event, the basic question is somewhat language agnostic. Variations of it have been asked on Stack Overflow for just about all programming languages, with the answer being essentially the same (unless the language in question already implements it in a library). – John Coleman Jun 19 '19 at 13:01
  • You are right, I've voted to close as duplicate. I'm getting a coffee. – Luca Cappelletti Jun 19 '19 at 13:06

1 Answers1

-1

Generate one random float value from 0 to sum of all probabilities.

float probabilities[] = [0.1, 0.2, 0.1, 0.15, 0.05, 0.1, 0.4];

float x = 0.0000001+(float)rand()/(float)(RAND_MAX/sum_probabilites);
float temp = 0;
int i=0;
int n = 7;
int number = 0;
for(i=0; i<n; i++)
{
   temp+=probabilites[i];
   if(x<=temp)
   {
       number = i+1;
       break;
   }

}
// int number contains value

Main idea is that you generate one float number and check if number belongs to range of probabilities.

Elbek
  • 616
  • 1
  • 4
  • 15