This question already has an answer here:
-
changing probability of getting a random number
7 answers
-
generating random number with a specific distribution in c
2 answers
By using rand()
function, we can create a possibility of an output.
Like rand()%4 + 'A'
basically means this code will generate random alphabets from A to D.
Then my question is, can we put "possibility rate" into this random generation?
Such as, for A to come out among 4 Alphabets ( from A to D), there only will be 24% chance
while B will come out at 12% rate, etc.
- I am using Windows and my program for coding is Visual Studio 2012. (The language is C)
Create a string of 100 letters, with 24 A's, 12 B's, and appropriate numbers of C's and D's. Generate a random number between 0 and 99; use this as an index into the string. That gives you your weighted random selection.
That's a simple but almost graphical way to do it. You can decide based on ranges too.
Such as, for A to come out among 4 Alphabets ( from A to D), there only will be 24% chance while B will come out at 12% rate, etc.
Yes, of course you can do that. Just select a number between 1 and 100. If the number is in the range [1, 24], the result is A. If the number is in the range [25, 36], the result is B, and so on.
The key is that you can map more than one result from the random function onto each outcome, and doing so allows you to adjust the frequency of each outcome.
You can do that by assigning a % to each outcome. Stack percents so that A goes from 0 to 25, B from 26 to 31, etc.. Now generate random number within 0..99 range and see which area it hit. Visually it looks like so:
<--A 25%--><-B 5%-><---C30%---><-----D40%----->