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) 
4
  • @Blaze hesitant at that. The accepted answer is somewhat adaptable but clearly all other answers there are very much C++ only. Commented Jun 19, 2019 at 12:58
  • @Blaze in particular there it works since the weights are integers, these are floats. Commented Jun 19, 2019 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). Commented Jun 19, 2019 at 13:01
  • You are right, I've voted to close as duplicate. I'm getting a coffee. Commented Jun 19, 2019 at 13:06

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.