Un-repeated Random Variables


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

Generating Array of Un-repeated Random Variables In User-Defined Bounds


Copy this code and paste it in your HTML
  1. <?php
  2. function GetUnrepeatedRandomVariables($minIndex,$maxIndex)
  3. {
  4. $res = array();
  5.  
  6. while(1)
  7. {
  8. if(count($res) == ($maxIndex-$minIndex+1))
  9. break;
  10. $rand = rand($minIndex, $maxIndex);
  11. if(!in_array($rand, $res))
  12. array_push ($res, $rand);
  13. }
  14. return $res;
  15. }
  16.  
  17. $arr = GetUnrepeatedRandomVariables(0, 10);
  18. print (count($arr) ."<br />");
  19. foreach ($arr as $val)
  20. print($val ."<br />");
  21. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.