Jump to content

Complete newbie - probability based on an argument?


ladyath

Recommended Posts

Not sure if anyone can help me with something like this.  I am looking for a php script that can give me the following:

 

Webpage with a dropdown listing the numbers 1 to 5.  Depending on what number is chosen, to execute a script to give me a set of results.

 

The results would be drawn from 5 tables.  In the tables there would be an item listed with a category flag of red, blue, green or yellow.

 

 

For example:  If the rating is 2: 

* display 4 random results from table 1 where the category is red

* display 2 random result from table 2 where the category is red

* 20% chance to display a result from the blue category in table 1 or two.

 

If the rating is 3: 

* display 5 random results from table 1 where the category is red

* display 3 random result from table 2 where the category is red

* display 1 random result from table 3 where the category is red

* 20% chance to display a result from the blue category in table 1 or two

* 5% chance to display a result from the green category in table 1 or two

 

How can this be done?  Sorry, but my knowledge on PHP is dismal at best :(

A 20% probability means that you have a 20/100 probability of that happening. You can just pick a random number like mt_rand(1, 100) and declare 20 of them the "positive" choice. Assuming that the output of PHP's PRNG is uniformly distributed, you can simply just choose the lower 20.

 

Thus, you should be able to do it like this:

function iCantThinkOfAGoodNameForThisFunction($probability)
{
    return mt_rand(1, 100) <= $probability;
}

 

Then there should be a 20% probability that iCantThinkOfAGoodNameForThisFunction(20) returns true.

Thank you for the response, but how would I have all 5 criteria?  Would it use a switch or an if statement?  I am a bit lost on how to approach it.

If I understand your desired result, I'd use a switch. Can you elaborate on what you're doing or display some code?

A 20% probability means that you have a 20/100 probability of that happening. You can just pick a random number like mt_rand(1, 100) and declare 20 of them the "positive" choice. Assuming that the output of PHP's PRNG is uniformly distributed, you can simply just choose the lower 20.

 

Thus, you should be able to do it like this:

function iCantThinkOfAGoodNameForThisFunction($probability)
{
    return mt_rand(1, 100) <= $probability;
}

 

Then there should be a 20% probability that iCantThinkOfAGoodNameForThisFunction(20) returns true.

 

It helped me a lot, thanks! :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.