i can generate random number between two numbers in c using this..
arc4random()%(high-low+1)+low;
then now my requirement is...i want to make a number rare....thats mean if
high=5, low=1, and rare=3,
than 3 will be appeared much rarely than 1,2,4 and 5...
Thanks
You can use tables to calculate your final roll, similar to how pen and paper RPGs do this same type of calculation:
Roll 1 D 21 (easily possibly w/ code).
The advantage to this option is you get a strong sense of the exact probabilities you are dealing with. You can get a feeling of exactly how rare or common each number is, and you get fine-grained control of how common each number is, in comparison to the other numbers.
You could also use fractions to generate the table. Use the Least Common Multiple to determine a common base. That base is the max random number size you will need. Then, put all the fractions in like terms. Use the resulting numerators to determine the size of the range for each number in the table.
With this automated solution, the input numbers are very easy to understand in relation to each other. E.g:
This would generate a table like so:
LCM = 20
Some more on LCM: http://en.wikipedia.org/wiki/Least_common_multiple
One simple-to-understand option:
There are other alternative approaches which would only require you to generate a single number, but the above feels like it would be the simplest one to write and understand.
You could create an array containing the numbers according to their probability:
list = (1, 1, 2, 2, 3, 4, 4, 5, 5);
return list.itemAtIndex(random() % list.count());
This is not very elegant, but it works and easily scales should the probabilities get more complex.
The sum of all probabilities must be 1. Now we are working here with discrete probabilities over a finite range so we are looking at (here) 5 possibilities with some distribution you have, call them p1, p2, p3, p4 and p5 the sum of which is 1.
f0 = 0 f1 = p1 f2 = f1 + p2 f3 = f2 + p3 f4 = f3 + p4 f5 = f4 + p5 and must be 1
Generate a random number from 0 to 1 and we will assume it cannot be exactly 1. Look at the f value that fits into its ceiling and that is the value of your random event. So perhaps
f1 = 0.222 f2 = 0.444 f3 = 0.555 f4 = 0.777 f5 = 1
If your random number is 0.645 then you have generated a 4 event. With the above you have half as much chance of generating a 3 than any of the others. We can make it less likely still, eg:
f1 = 0.24 f2 = 0.48 f3 = 0.52 f4 = 0.76 f5 = 1
0.24 probably of the others and only 0.04 of a 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With