PhpNewb314 Posted March 9, 2014 Share Posted March 9, 2014 I wonder how I can execute an action which has x% chance of happening, for instance a 31% chance of happening. How would I do that? I was thinking of using rand() to generate a number between 1 and 100 and if it is <= 50 (or whatever the percentage is, since that is going to vary based on the rank of the individual and hopefully fluctuate within ranks) then it is successful and if it is >50 then it isn't successful. This is just a preliminary idea and is definitely going to get more complex since I need to vary the percentage depending on rank and even slight fluctuation within rank (it is a game) but I was wondering about the best way to do this aspect of it. Is this the best way or is there a more efficient (or more elegant) way? Thanks for any advice! Quote Link to comment Share on other sites More sharing options...
.josh Posted March 9, 2014 Share Posted March 9, 2014 that's how you do it, yes. function probability($p) { return $p >= rand(1,100); } if ( probability(31) ) echo 'true'; else echo 'false'; Quote Link to comment Share on other sites More sharing options...
Solution PhpNewb314 Posted March 9, 2014 Author Solution Share Posted March 9, 2014 that's how you do it, yes. function probability($p) { return $p >= rand(1,100); } if ( probability(31) ) echo 'true'; else echo 'false'; I thought that was probably the best way. Thank-you for confirming this, Josh! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.