Random with Percentage Generator


/ Published in: PHP
Save to your folder(s)

Here is an example where the likelihood of NS is 30%, SM is 50%, and SH is 20%. I make 20 pitches and output what the batter does each time.


Copy this code and paste it in your HTML
  1. <?php
  2. $percentNS = 0.3;
  3. $percentSM = 0.5;
  4. $percentSH = 1.0 - $percentNS - $percentSM;
  5.  
  6. $upperBoundNS = $percentNS;
  7. $upperBoundSM = $percentNS + $percentSM;
  8. $upperBoundSH = 1.0;
  9.  
  10. for ($i = 0; $i < 20; $i++) {
  11. $rand = rand(0, 100);
  12. $rand = $rand / 100.0;
  13.  
  14. if ($rand < $upperBoundNS) {
  15. echo 'not swing';
  16. }
  17. else if ($rand < $upperBoundSM) {
  18. echo 'swing and miss';
  19. }
  20. else {
  21. // $rand < $upperBoundSH
  22. echo 'swing and hit';
  23. }
  24.  
  25. echo '<br />';
  26. }
  27. ?>

URL: http://www.kirupa.com/forum/showthread.php?t=344243

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.