Junaid
Junaid

Reputation: 2094

Calculating probability with given ranges

In a couple of last application I was supposed to implement Probability which was usually given among some items say:

reward a user on certain level completion item X

item X may be one of the below:

jug => probability 25
glass => probability 50
plate => probability 20
dish => probability 5

I solve this by creating an array and populating the specific item the number of times its probability is; for the above case I would have an array with 25 elements of jug, 50 glasses and so on.. and I finally shuffle {PHP} the array a few time and select a random element from it.

in another application the values were totaling more than 100 so I first calculated their respected percentages from that total and then used the above logic.

Just want to know if this is the right way to calculate probability from such a structure?

I have gone through a couple of issues here on SOF but none helped me in my case.

If there is more appropriate way to do this please let me know

Thanks

Upvotes: 0

Views: 2036

Answers (2)

Florin Mircea
Florin Mircea

Reputation: 973

You may simply assign the following values:

$jug = 25;
$glass = 25+50 = 75;
$plate = 75+20 = 95;
$dish = 95+5 = 100

Then obtain a random of 100 and determine where it fits, similar to the pseudocode below:

$jug = 25;
$glass = 75;
$plate = 95;
$dish = 100;
$items = {"jug", "glass", "plate", "dish"};

$rand = random(100);  // Get a random number between 0 and 100

if ($rand < $jug) {
    return items(0);
} elseif ($rand < $glass) {
    return items(1);
} elseif ($rand < $plate) {
    return items(2);
} elseif ($rand < $dish) {
    return items(3);
}

Hope this helps.

Upvotes: 4

Voitcus
Voitcus

Reputation: 4446

I would do this the same way as you, but you don't have to calculate percentages, you may use more than 100 elements.

For example, if A=80 and B=40, you may use the array with 120 elements.

However, in mathematics there is a term greatest common divisor that you can reduce the number of elements. In this example, the GCD is 40 so A would be 2 and B would be 1, and your array size would decrease to 3 elements. It might be important for example when total number of elements is quite large.

Upvotes: 0

Related Questions